Open3

Laravelで独自フォーマットログをjson形式で標準出力する

tenryutenryu

FormatterInterfaceを実装したクラスを定義し、logging.phpのformatterで指定する。

logging.php
'stderr' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'debug'),
            'handler' => StreamHandler::class,
            'with' => [
                'stream' => 'php://stderr',
            ],
            'formatter' => App\Logging\CustomFormatter::class,
        ],
CustomFormatter.php
use Monolog\Formatter\FormatterInterface;

class CustomFormatter implements FormatterInterface
{
    public function format(array $record)
    {
        // 任意のフォーマットに変換
        return '[' . $record['datetime']->format('Y-m-d H:i:s') . '] ' . $record['message'] . PHP_EOL;
    }

    public function formatBatch(array $records)
    {
        $output = '';
        foreach ($records as $record) {
            $output .= $this->format($record);
        }
        return $output;
    }
}

https://www.tukatech.jp/techblog/【phpエンジニア必見】monologライブラリを使いこなす!/

tenryutenryu

LaravelでLogファサードを使用し、Monolog\Formatter\JsonFormatterをフォーマッタとして指定すると以下のようにログが出力される。

api.php
    Log::debug('ジョブの生成に成功.',[
        'job_id' => 3234,
    ]);
{"message":"ジョブの生成に成功.","context":{"job_id":3234},"level":100,"level_name":"DEBUG","channel":"local","datetime":"2023-12-25T23:53:52.074037+00:00","extra":{}}

デフォルトで定義されているこのフォーマットを変更したい。
例:datetimeをtimeに変更、など
https://zenn.dev/knowledgework/articles/cloud-logging-special-payload-fields#time

tenryutenryu
$formatted = array_map([$this, 'format'], $records);

[$this, 'format']
このインスタンスのformat()をコールバックに指定、$recordsの各要素へ適用