0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelのログフォーマットのカスタムで改行が効かない時

0
Last updated at Posted at 2021-04-17

はじめに

Laravelでログのフォーマットを変更しようとした時に改行が思ったように効かない、そんな時の対処法

Laravelでログフォーマットを変更する方法

フォーマットを変更したいログのチャンネルに'tap' => [App\Logging\CustomizeFormatter::class],を追加

'channels' => [
        'stack' => [
            'driver' => 'stack',
            'tap' => [App\Logging\CustomizeFormatter::class],
            'channels' => ['error', 'app'],
            'ignore_exceptions' => false,
        ],
]

app/Logging/CustomizeFormatter.phpを作成してログのフォーマットを記述していきます
laravel8のリファレンスに記載のコードは以下

<?php

namespace App\Logging;

use Monolog\Formatter\LineFormatter;

class CustomizeFormatter
{
    /**
     * 指定するロガーインスタンスをカスタマイズ
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                '[%datetime%] %channel%.%level_name%: %message% %context% %extra%'
            ));
        }
    }
}

このコードのままだと改行が効かずにログが一行で出力され続けます。見にくくて不便。

加えて改行のために末尾に \nを追加して'[%datetime%] %channel%.%level_name%: %message% %context% %extra%'\nとしても改行は効きません。

ログを改行させて表示したい

LineFormatterクラスを参照すると

public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false)
    {
        $this->format = $format === null ? static::SIMPLE_FORMAT : $format;
        $this->allowInlineLineBreaks = $allowInlineLineBreaks;
        $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
        parent::__construct($dateFormat);
    }

第三引数がbool $allowInlineLineBreaks = falseで改行の可否を定めるものでありデフォルト値がfalseになっていることがわかります。
思うように改行が効かなかったのはこいつのせい。

ついでに第二引数を見ると?string $dateFormat = nullとなっていて日時のフォーマットを引数で渡すことができます。便利。

これらを踏まえてコードを書き換えると

<?php


namespace App\Logging;

use Monolog\Formatter\LineFormatter;

class CustomizeFormatter
{
    /**
     * 指定するロガーインスタンスをカスタマイズ
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", 'Y/m/d H:i:s', true
            ));
        }
    }
}

出力されるログは以下のようになります。
改行が効いていること。日時フォーマットが指定したものになっていることが確認できました。

[2021/04/17 13:51:19] local.ERROR: this is error log [] []
[2021/04/17 13:51:23] local.INFO: this is info log [] []
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?