LoginSignup
57

More than 5 years have passed since last update.

Laravelのログにファイル名やメソッド名を出力する

Last updated at Posted at 2015-04-12

Monologではログ出力にメッセージ以外に情報を付加する2つのフィールドがあります。

1つ前の記事を例に挙げると、

[2015-04-21 13:25:42] local.INFO: hello [] []

の最後の2つの[]です。1つはcontext、もう1つはextraと呼ばれます。

contextはログ出力時に引数で指定することができ、extraはLoggerに与えられたProcessorが呼び出されることによって付与されます。

例えば、このようにcontextに情報を与えれば:

        \Log::info("hello", ['file' => __FILE__, 'line' => __LINE__]);

このように出力されます。

[2015-04-21 13:30:06] local.INFO: hello {"file":"C:\\path\\to\\app\\Http\\Controllers\\WelcomeController.php","line":39} []

このような情報をextraフィールドに自動的に追加するのがMonolog\Processor\IntrospectionProcessorです。LoggerにIntrospectionProcessorを追加します。

        $monolog = Log::getMonolog();
        $ip = new \Monolog\Processor\IntrospectionProcessor();
        $monolog->pushProcessor($ip);

出力はこうなります。

[2015-04-21 13:34:17] local.INFO: hello [] {"file":"C:\\path\\to\\vendor\\laravel\\framework\\src\\Illuminate\\Log\\Writer.php","line":201,"class":"Illuminate\\Log\\Writer","function":"writeLog"}

確かにWrite::writeLogからログ出力されてはいるのですが、これだとログとしては役に立ちません。IntrospectionProcessorではログ出力時のスタック上でスキップするクラスを指定することができます(デフォルトではMonolog\\と前方一致するもののみスキップします)。

        $monolog = Log::getMonolog();
        $ip = new \Monolog\Processor\IntrospectionProcessor(
            \Monolog\Logger::DEBUG,
            [
                'Monolog\\',
                'Illuminate\\',
            ]
        );
        $monolog->pushProcessor($ip);

出力はこうなります。

[2015-04-21 13:36:15] local.INFO: hello [] {"file":"C:\\path\\to\\app\\Http\\Controllers\\WelcomeController.php","line":39,"class":"App\\Http\\Controllers\\WelcomeController","function":"index"}

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
57