如何更改laravel日志格式?

时间:2016-09-21 20:35:11

标签: php laravel logging laravel-5 laravel-5.2

我需要将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":[

   ]
}

1 个答案:

答案 0 :(得分:4)

<强>自举/ 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;
    }

}