写邮件到日志时是php monolog换行吗?

时间:2014-04-04 07:38:33

标签: php logging monolog

我有一段代码。

class LogApi {

    private $log;
    private $path;
    private $format = array(
        'date' => 'Y-m-d H:i:s',
        'message' => '[%datetime%][%channel%][%level_name%] : %message% %context%',
    );
    private $formatter;

    function __construct() {
        $this->log =  new \Monolog\Logger('Log');
        $this->path = LOG_ADMIN_REDIS_INIT_FILE;
        $this->formatter = new \Monolog\Formatter\LineFormatter($this->format['message'], $this->format['date']);

    }

    public function log($path = LOG_ADMIN_REDIS_INIT_FILE, $level = Monolog\Logger::INFO){

        $stream = new \Monolog\Handler\StreamHandler($path, $level);
        $stream->setFormatter($this->formatter);
        $this->log->pushHandler($stream);

        $this->log->addInfo('Mytest', array('name'=>'John'));
    }
}

这是日志信息:

  

[2014-04-04 07:20:41] [日志] [信息]:Mytest {“name”:“John”}

但如果我有更多的日志,那么一切都在一行。

  

[2014-04-04 07:20:41] [日志] [信息]:Mytest {“name”:“John”} [2014-04-04 07:20:41] [日志] [INFO] :Mytest {“name”:“John”} [2014-04-04 07:20:41] [Log] [INFO]:Mytest {“name”:“John”}

当我使用StreamHandler时,我会查看其源代码

protected function write(array $record)
{
    if (null === $this->stream) {
        if (!$this->url) {
            throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
        }
        $errorMessage = null;
        set_error_handler(function ($code, $msg) use (&$errorMessage) {
            $errorMessage = preg_replace('{^fopen\(.*?\): }', '', $msg);
        });
        $this->stream = fopen($this->url, 'a');
        restore_error_handler();
        if (!is_resource($this->stream)) {
            $this->stream = null;
            throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: '.$errorMessage, $this->url));
        }
    }
    fwrite($this->stream, (string) $record['formatted']);
}

它只是在日志文件中添加消息。

所以我的问题是:我是否需要自己处理wrap line,或者monolog已经提供了包裹线的功能?

提前致谢。

1 个答案:

答案 0 :(得分:1)

哦不,我的错。

private $format = array(
    'date' => 'Y-m-d H:i:s',
    'message' => '[%datetime%][%channel%][%level_name%] : %message% %context%',
);

它的简单,只是这样的配置格式:

'message' => '[%datetime%][%channel%][%level_name%] : %message% %context% \n',

但我发现不行。

但这有效

'message' => "[%datetime%][%channel%][%level_name%] : %message% %context% \n",

因此请使用双引号