30.2. Writers

一个Writer是继承自Zend_Log_Writer_Abstract类的一个对象.Writer的职责是向存储后端纪录日志数据.

30.2.1. 写入到流(Streams)

Zend_Log_Writer_Stream 写入日志数据到 PHP 流中.

要把日志写入到输出缓冲区,使用URLphp:://output. 或则你可以直接发送日志数据到像STDERR 这样的流中(php://stderr).

$writer = new Zend_Log_Writer_Stream('php://output');
$logger = new Zend_Log($writer);

$logger->info('Informational message');

      

写入日志数据到一个文件,使用Filesystem URLs之一:

$writer = new Zend_Log_Writer_Stream('/path/to/logfile');
$logger = new Zend_Log($writer);

$logger->info('Informational message');

      

默认情况流一个追加("a")的方式打开.要以不同的模式打开,Zend_Log_Writer_Stream 构造函数接受第二个参数作为可选的模式参数.

Zend_Log_Writer_Stream还接受一个现有的流资源:

$stream = @fopen('/path/to/logfile', 'a', false);
if (! $stream) {
    throw new Exception('Failed to open stream');
}

$writer = new Zend_Log_Writer_Stream($stream);
$logger = new Zend_Log($writer);

$logger->info('Informational message');

      

你不能给现有的流资源指定模式.这样作将导致抛出一个Zend_Log_Exception异常.

30.2.2. 写入到数据库

Zend_Log_Writer_Db使用Zend_Db写入日志信息到数据库表中. Zend_Log_Writer_Db的构造函数接受一个Zend_Db_Adapter 实例,一个表名,和一个数据库字段到事件数据项的映射:

$params = array ('host'     => '127.0.0.1',
                 'username' => 'malory',
                 'password' => '******',
                 'dbname'   => 'camelot');
$db = Zend_Db::factory('PDO_MYSQL', $params);

$columnMapping = array('lvl' => 'priority', 'msg' => 'message');
$writer = new Zend_Log_Writer_Db($db, 'log_table_name', $columnMapping);

$logger = new Zend_Log($writer);

$logger->info('Informational message');

      

上面的例子写入单个行到名称为log_table_name的数据库表中.数据库字段lvs 接收优先级号,名为msg的字段接收日志消息.

30.2.3. Writing to Firebug

Zend_Log_Writer_Firebug sends log data to the Firebug Console.

All data is sent via the Zend_Wildfire_Channel_HttpHeaders component which uses HTTP headers to ensure the page content is not disturbed. Debugging AJAX requests that require clean JSON and XML responses is possible with this approach.

Requirements:

例 30.1. Logging with Zend_Controller_Front

// Place this in your bootstrap file before dispatching your front controller
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);

// Use this in your model, view and controller files
$logger->log('This is a log message!', Zend_Log::INFO);

      

例 30.2. Logging without Zend_Controller_Front

$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);

$request = new Zend_Controller_Request_Http();
$response = new Zend_Controller_Response_Http();
$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
$channel->setRequest($request);
$channel->setResponse($response);

// Start output buffering
ob_start();

// Now you can make calls to the logger

$logger->log('This is a log message!', Zend_Log::INFO);

// Flush log data to browser
$channel->flush();
$response->sendHeaders();

      

30.2.3.1. Setting Styles for Priorities

Built-in and user-defined priorities can be styled with the setPriorityStyle() method.

$logger->addPriority('FOO', 8);
$writer->setPriorityStyle(8, 'TRACE');
$logger->foo('Foo Message');

      

The default style for user-defined priorities can be set with the setDefaultPriorityStyle() method.

$writer->setDefaultPriorityStyle('TRACE');

      

The supported styles are as follows:

表 30.1. Firebug Logging Styles

Style Description
LOG Displays a plain log message
INFO Displays an info log message
WARN Displays a warning log message
ERROR Displays an error log message that increments Firebug's error count
TRACE Displays a log message with an expandable stack trace
EXCEPTION Displays an error long message with an expandable stack trace
TABLE Displays a log message with an expandable table


30.2.3.2. Preparing data for Logging

While any PHP variable can be logged with the built-in priorities, some special formatting is required if using some of the more specialized log styles.

The LOG, INFO, WARN, ERROR and TRACE styles require no special formatting.

30.2.3.3. Exception Logging

To log a Zend_Exception simply pass the exception object to the logger. It does not matter which priority or style you have set as the exception is automatically recognized.

$exception = new Zend_Exception('Test exception');
$logger->err($exception);

      

30.2.3.4. Table Logging

You can also log data and format it in a table style. Columns are automatically recognized and the first row of data automatically becomes the header.

$writer->setPriorityStyle(8, 'TABLE');
$logger->addPriority('TABLE', 8);

$table = array('Summary line for the table',
             array(
                 array('Column 1', 'Column 2'),
                 array('Row 1 c 1',' Row 1 c 2'),
                 array('Row 2 c 1',' Row 2 c 2')
             )
            );
$logger->table($table);

      

30.2.4. 踩熄Writer

Zend_Log_Writer_Null是一个不向任何地方写入任何数据的存根. 用于在测试期间关闭或踩熄日志.

$writer = new Zend_Log_Writer_Null;
$logger = new Zend_Log($writer);

// goes nowhere
$logger->info('Informational message');

      

30.2.5. 测试 Mock

Zend_Log_Writer_Mock是一个非常简单的Writer,它纪录所接收到的原始的数据到到作为public属性的 数组中.

$mock = new Zend_Log_Writer_Mock;
$logger = new Zend_Log($mock);

$logger->info('Informational message');

var_dump($mock->events[0]);

// Array
// (
//    [timestamp] => 2007-04-06T07:16:37-07:00
//    [message] => Informational message
//    [priority] => 6
//    [priorityName] => INFO
// )

      

清空有mock记录的日志,设置$mock->events = array()即可.

30.2.6. 组合Writers

没有复合Writer对象,但是一个Log实例可以有任意个Writer.使用addWriter方法 添加Writer:

$writer1 = new Zend_Log_Writer_Stream('/path/to/first/logfile');
$writer2 = new Zend_Log_Writer_Stream('/path/to/second/logfile');

$logger = new Zend_Log();
$logger->addWriter($writer1);
$logger->addWriter($writer2);

// goes to both writers
$logger->info('Informational message');