Monologのfingers_crossedがようやくわかった

MonologはSymfony2でも利用されている高機能なロガーライブラリです。PythonLogbookというライブラリをPHPに移植したものだと記憶しています。

Symfony2の app/config/config_dev.yml では、Monologは次のように設定されています。

monolog:
    handlers:
        main:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug

これはそのまま、debug以上のレベルのログをpathに指定したログファイルに書き出すという指定です。config_dev.phpなので開発環境用の設定ファイルですが、ログはすべて書き出すという設定です。

これとは別に、運用環境用の config_prod.yml では次のように設定されています。

monolog:
    handlers:
        main:
            type:         fingers_crossed
            action_level: error
            handler:      nested
        nested:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug

nestedという部分はconfig_dev.ymlのものと同一です。それとは別に、fingers_crossedという typeのハンドラーが設定されています。今までこのfingers_crossedというのが何かよくわからなかったので調べてみました。

上記のconfig_prod.ymlの設定だとどのようになるかというと、ログレベルがerror以上のログが記録された場合のみログを出力するが、そのときはそれまでに記録されたdebug以上のすべてのログが出力されます。

FingersCrossedHandler: A very interesting wrapper. It takes a logger as parameter and will accumulate log records of all levels until a record exceeds the defined severity level. At which point it delivers all records, including those of lower severity, to the handler it wraps. This means that until an error actually happens you will not see anything in your logs, but when it happens you will have the full information, including debug and info records. This provides you with all the information you need, but only when you need it.

GitHub - Seldaek/monolog: Sends your logs to files, sockets, inboxes, databases and various web services

従来のロガーでは、error以上と設定した場合、error以上のログのみが記録されます。しかし、エラーが出た場合はより詳細なログがみたいというものです。このfingers_crossedを用いると、エラーがあったプロセスはデバッグ情報も含めたログが残るため、エラーの追求などが容易になります。

今までは運用環境ではデバッグログなんかは出力しないようにしていましたが、それでもログを残すように設定しておいて損はないなと思いました。