Monolog

Monolog とは

MonologはPHPのロギングライブラリでSymfony2やLaravelで採用されています。
使ってみるとすごく便利でしたのでおすすめです^^
https://github.com/Seldaek/monolog

基本的な使い方

これもcomposerで管理するときはこんな感じ

$ composer require monolog/monolog

もしくはcomposer.jsonでこんな感じ

{
    "require": {
        "monolog/monolog": "@stable"
    },
}

ここはドキュメント通りです

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->debug('this is debug');
$log->warning('this is warning');
$log->error('this is error');

StreamHandlerの第二引数で閾値を決めることができます。
この場合は warning と error ログが出力され debug ログは出力されません。

Handler

いくつかのハンドラーを紹介します

Handler -
StreamHandler ログファイルにログを出力します
RotatingFileHandler ログを出力するとともに1日のログを別ファイルにします
SwiftMailerHandler ログ発生時にメールを送信します
FingersCrossedHandler ある一定のレベルを超えたらログを出力します。

pushHandlerを使うことでこれらのハンドラーを組み合わせて使うことができます。

一定のログレベルを超えたら詳細にログを出力する

FingersCrossedHandlerを使うことで、ERRORが発生したらINFOレベルのログもすべて出力する。といった使い方ができます。

$logger->pushHandler(
    new FingersCrossedHandler(
        new RotatingFileHandler($logging_path, 2, Logger::INFO),
        new ErrorLevelActivationStrategy(Logger::ERROR)
    )
);

さらに

ERROR以上のログが落ちた場合はINFOログ以上を出したいが、NOTICEログは常に出したいという場合があると思います。

FingersCrossedHandler の constructor を見ると、常にログを落とす最低限のログレベルを指定できるようです。
https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/FingersCrossedHandler.php

    /**
     * @param callable|HandlerInterface       $handler            Handler or factory callable($record, $fingersCrossedHandler).
     * @param int|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action
     * @param int                             $bufferSize         How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
     * @param Boolean                         $bubble             Whether the messages that are handled can bubble up the stack or not
     * @param Boolean                         $stopBuffering      Whether the handler should stop buffering after being triggered (default true)
     * @param int                             $passthruLevel      Minimum level to always flush to handler on close, even if strategy not triggered
     */
    public function __construct($handler, $activationStrategy = null, $bufferSize = 0, $bubble = true, $stopBuffering = true, $passthruLevel = null){}

こんな感じでいけると思います。

$logger->pushHandler(
    new FingersCrossedHandler(
        new RotatingFileHandler($logging_path, 2, Logger::INFO),
        new ErrorLevelActivationStrategy(Logger::ERROR),
        0,
        true,
        true,
        Logger::NOTICE
    )
);