Custom Zend Log Format: Security Logging
Saturday, August 25. 2007
The default file logging format for Zend_Log File Writer is as folows:
%timestamp% %priorityName% (%priority%): %message%
Which is fine for error logging. For other sorts of logging like security auditing, We need more, like an IP of the visitor and a hostname. Other sorts of logging you might want to log things like the request where the error occurred. This is very easy to do with Zend_Log, however this really isn't documented and I've found people doing weird things like extending Zend_Log to achieve this. Let's look how to do this right.
//first we create a file writer $stream = new Zend_Log_Writer_Stream('./path/to/logs/sec.log'); //then we create a log formatter, note that we changed the default //fields to add the user ip and the user host of the request. $formatter = new Zend_Log_Formatter_Simple('%userip% - %userhost% - [%timestamp%] %priorityName%: %message%' . PHP_EOL); //now we add the new formatter to the writer $stream->setFormatter($formatter); //then we add the writer to create a new logging instance $logger = new Zend_Log($stream); //now we give meaning to the newly added fields. //I also changed the default format of the timestamp $logger->setEventItem('userip',$_SERVER['REMOTE_ADDR']); $logger->setEventItem('userhost',gethostbyaddr($_SERVER['REMOTE_ADDR'])); $logger->setEventItem('timestamp', date('m-d-Y H:i:s', time())); //now in our code we can log away $logger->emerg("User Failed Login");
In our log we'll get nice messages with IP and Host:
127.0.0.1 - localhost - [08-22-2007 21:54:30] EMERG: User Failed Login
RSS 1.0 Feed





Comments
No comments