LoginSignup
3
2

More than 3 years have passed since last update.

AWSにデプロイしたLaravelのログを見やすくした

Posted at

はじめに

ECSにLaravelをデプロイしているときにCloudWatchLogsにログを吐いていたが
不具合が起こったときに調査しやすくするためにlogをjson化してなおかつ
同一リクエストのログをまとめて取得したかった

前提

ECSにデプロイしているALBを使用している時

コード

ALBを経由したリクエストにはX-Amzn-Trace-Idというヘッダーに
リクエストごとに固有のIDが振られるのでログに吐いておくと
あとで確認しやすい

app/Log/JsonFormatter.php
<?php

declare(strict_types=1);

namespace App\Log;

use Illuminate\Http\Request;
use Monolog\Formatter\NormalizerFormatter;

class JsonFormatter extends NormalizerFormatter
{
    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $request = resolve(Request::class);
        $output = [];
        $output['level'] = $record['level_name'];
        $output['xAmznTraceId'] = $request->header('X-Amzn-Trace-Id');
        $output['message'] = $record['message'];
        foreach ($record['context'] as $var => $val) {
            $output[$var] = $val;
        }

        return json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
    }
}

phpコンテナの出力はstderrに出てくるので
logging.phpを以下のように修正

config/logging.php
       'stderr' => [
            'driver'    => 'monolog',
            'handler'   => StreamHandler::class,
            'formatter' => \App\Log\JsonFormatter::class,
            'with'      => [
                'stream' => 'php://stderr',
            ],
        ],
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2