Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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"}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした