gpt4 book ai didi

php - 如何更改laravel日志格式?

转载 作者:行者123 更新时间:2023-12-04 01:51:33 26 4
gpt4 key购买 nike

我需要将 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",
}

这该怎么做?

我尝试将下一个代码放在 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);
});

这是结果:
{
"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":[

]
}

最佳答案

bootstrap /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
<?php

namespace App\Components\Log\Formatter;

use Monolog\Formatter\JsonFormatter as BaseJsonFormatter;

/**
* Class JsonFormatter
*
* @package App\Components\Log\Formatter
* @author Miguel Borges <miguelborges@miguelborges.com>
*/
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;
}

}

关于php - 如何更改laravel日志格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com