将消息写入日志时,php独白是否换行?
我有一段代码将消息写入日志时,php独白是否换行?,php,logging,monolog,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; fu
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][日志][信息]:我的测试{“姓名”:“约翰”}
但如果我有更多的日志,所有内容都在一行中
[2014-04-04 07:20:41][Log][INFO]:Mytest{“name”:“John”}[2014-04-04 07:20:41][Log][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']);
}
它只是将消息附加到日志文件中
所以我的问题是:我需要自己处理换行
,还是独白已经提供了换行功能
提前谢谢。哦,不,是我的错
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",
因此,在fwrite中使用双引号有帮助吗?我不想修改独白的源代码,所以可能无法使用建议。但是仍然要感谢一点关于为什么这不起作用的说明:当使用单引号时,PHP不会解析像
\n
这样的转义字符。双引号可以解析它们。您还可以使用常量PHP\u EOL
。