How to change laravel logs format?

11,631

Solution 1

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 <[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;
    }

}

Solution 2

You can set log formatter for the log channel you use in config/logging.php file.

    'channels' => [
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
            // THIS IS THE LINE YOU SHOULD ADD TO CHANGE FROMAT TO JSON
            'formatter' => Monolog\Formatter\JsonFormatter::class,
        ],

        // Other channels
];
Share:
11,631
Miguel Borges
Author by

Miguel Borges

I'm a Eng. of Software and Web Developed

Updated on June 04, 2022

Comments

  • Miguel Borges
    Miguel Borges almost 2 years

    I need change the format of laravel logs to json format like this:

    {
       "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.

    $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":[
    
       ]
    }
    
  • Lauri Elias
    Lauri Elias about 6 years
    Mostly your solution has been very helpful, but I've gotten a few headaches from JSON serialization failing silently.
  • miniGweek
    miniGweek over 2 years
    This worked for me! Thank you very much! :-) Simple and straightforward!