Monolog JsonFormatter没有格式化我的代码?

时间:2016-03-02 06:49:09

标签: php monolog

我在这里阅读了很多问题并阅读了一些文档。但仍然不明白如何使用monolog格式化JSON值。

这里我的代码无效:

php $formatter = new JsonFormatter(); $log->addInfo($formatter->format(['foo' => 'bar']));

输出始终在一行而不是格式化。

bash [2016-03-02 07:45:57] parameters.INFO: {"foo":"bar"} [] []

1 个答案:

答案 0 :(得分:5)

The JsonFormatter is meant to be used for formatting the output.

$log = new \Monolog\Logger( 'my_log' );
$stream_handler = new \Monolog\Handler\StreamHandler( 'my_log_file.log' );
$stream_handler->setFormatter( new \Monolog\Formatter\JsonFormatter() );
$log->pushHandler( $stream_handler );

$log->addError( 'foo' );

Without the JsonFormatter you get the normal output:

[2016-04-04 16:37:55] my_log.ERROR: foo [] [] 

With the JsonFormatter you get JSON output:

{"message":"foo","context":[],"level":400,"level_name":"ERROR","channel":"my_log","datetime":{"date":"2016-04-04 16:38:14.102258","timezone_type":3,"timezone":"UTC"},"extra":[]}