laravel 如何更改laravel日志格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39626116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change laravel logs format?
提问by Miguel Borges
I need change the format of laravel logs to json format like this:
我需要将 Laravel 日志的格式更改为 json 格式,如下所示:
{
"time":"2015-10-06 15:45:36",
"host":"192.000.000",
"protocol”:”http, tcp",
"remote-addrress": "192.000.001",
"user":"user-logged",
"level": "warning",
"message":"exception",
}
How to do this?
这该怎么做?
I try put the next code in bootstrap/app.php but I don't know how to change the json format/object.
我尝试将下一个代码放在 bootstrap/app.php 中,但我不知道如何更改 json 格式/对象。
$app->configureMonologUsing(function ($monolog) use ($app) {
// Stream handlers
$logPath = $app->storagePath().'/logs/test.log';
$logLevel = \Monolog\Logger::DEBUG;
$logStreamHandler = new \Monolog\Handler\StreamHandler($logPath, $logLevel);
$formatter = new \Monolog\Formatter\JsonFormatter();
$logStreamHandler->setFormatter($formatter);
$monolog->pushHandler($logStreamHandler);
});
this is the result:
这是结果:
{
"message":"info",
"context":[
],
"level":200,
"level_name":"INFO",
"channel":"local",
"datetime":{
"date":"2016-09-22 10:33:38.318064",
"timezone_type":3,
"timezone":"UTC"
},
"extra":[
]
}
回答by Miguel Borges
bootstrap/app.php
引导程序/app.php
$app->configureMonologUsing(function ($monolog) use ($app) {
// Stream handlers
$logPath = $app->storagePath() . '/logs/laravel.log';
$logLevel = \Monolog\Logger::DEBUG;
$logStreamHandler = new \Monolog\Handler\StreamHandler($logPath, $logLevel);
// Formatting
$formatter = new \App\Components\Log\Formatter\JsonFormatter();
$logStreamHandler->setFormatter($formatter);
$monolog->pushHandler($logStreamHandler);
});
app/Components/Log/Formatter/JsonFormatter.php
应用程序/组件/日志/格式化程序/JsonFormatter.php
<?php
namespace App\Components\Log\Formatter;
use Monolog\Formatter\JsonFormatter as BaseJsonFormatter;
/**
* Class JsonFormatter
*
* @package App\Components\Log\Formatter
* @author Miguel Borges <[email protected]>
*/
class JsonFormatter extends BaseJsonFormatter
{
const APPLICATION = 'My application';
/**
* {@inheritdoc}
*/
public function format(array $record)
{
$record = [
'time' => $record['datetime']->format('Y-m-d H:i:s'),
'application' => self::APPLICATION,
'host' => request()->server('SERVER_ADDR'),
'remote-addrress' => request()->server('REMOTE_ADDR'),
'level' => $record['level_name'],
'message' => $record['message']
];
if (!empty($record['extra'])) {
$record['payload']['extra'] = $record['extra'];
}
if (!empty($record['context'])) {
$record['payload']['context'] = $record['context'];
}
$json = $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : '');
return $json;
}
}