Wednesday, 14 March 2007

Extending the Zend_Log layout

Due to the solid updates and improvements of the Zend_Log component in the Beta 0.9.2 release, this article is outdated. Please have a look on the follow-up article "Zend_Log revisited" on this blog.

As the current Zend_Log component doesn't provide very meaningful log content per default I wanted to extend the information logged and also the logfile layout. In the article of Stefan Koopmanschap this issue is solved by using the setMessagePrefix method of the Zend_Log class, which pushs the additional log information and layout unlovely to the Bootstrap file.

Another way to improve the content and layout being logged is writing a custom Zend_Log_Adapter by extending for instance Zend_Log_Adapter_File and overwriting its _parseLogLine metod and redefining its _options array.

The possible adapter is located under ./libary/Recordshelf/Log/Adapter and must be in your PHP include_path.

<?php

class Recordshelf_Log_Adapter_File extends Zend_Log_Adapter_File {

private $_options = array('buffer' => false,
'bufferLines' => 20,
'keepOpen' => false,
'format' => '[%timestamp%] [%pid%] [%level%] %message%');

protected function _parseLogLine($fields) {

$output = $this->_options['format'];

$fields['timestamp'] = date('d.m.Y H:i:s');
$fields['pid'] = getmypid();

foreach($fields as $name => $value) {

$output = str_replace('%$name%', $value, $output);

}

return $output;

}

}
At last the custom adapter must be registered in the Bootstrap file,
...
Zend_Log::registerLogger(new Recordshelf_Log_Adapter_File('../logs/development.log'));
...
and now can be used by your application.
...
$dump = print_r($object, true);
Zend_Log::log(__METHOD__." Object: ${dump}", Zend_Log::LEVEL_INFO);
...
As the rewrite of Zend_Log is an offical approved proposal this whole issue might be solved in one of the following versions of the Zend Framework.

No comments: