ログにはレベルがあります。( PSR-3 )
PSR-3: Logger Interface: https://www.php-fig.org/psr/psr-3/
(危険な順)
8. EMERGENCY
7. ALERT
6. CRITICAL
5. ERROR
4. WARNING
3. NOTICE
2. INFO
1. DEBUG
このログレベルを利用して
・ログレベルが ERROR 以上の時はログに保存しつつメールで送信
・ログレベルが WARNING 以下の時はログに保存
という運用ができるように設定してみます。
コントローラーのコンストラクタに以下を記述
protected $monolog;
public function __construct()
{
// umask。適宜書き換えてください。
umask(0000);
$this->monolog = Log::getLogger(); // laravel 5.6以降
// 1. monolog - mail
$transport = new \Swift_SendmailTransport('/usr/sbin/sendmail -t');
$mailer = new \Swift_Mailer($transport);
$message = new \Swift_Message('monolog ERROR');
$message->setFrom('メールアドレス');
$message->setTo('メールアドレス');
$this->monolog->pushHandler(new \Monolog\Handler\SwiftMailerHandler($mailer, $message, \Monolog\Logger::ERROR, false));
// 2. monolog - file - rotation
$formatter = new \Monolog\Formatter\LineFormatter(null, null, true);
$handler = new \Monolog\Handler\RotatingFileHandler(storage_path('logs').DIRECTORY_SEPARATOR.'error.log', 10, \Monolog\Logger::ERROR );
$handler->setFormatter($formatter);
$this->monolog->pushHandler($handler);
}
次のメソッドでログに記録します。
ログファイルに記録
$this->monolog->debug('1. debug');
$this->monolog->info('2. info');
$this->monolog->notice('3. notice');
$this->monolog->warning('4. warning');
ログファイルに記録(ファイル名と行番号)
$this->monolog->info('ログメッセージ', ['file' => basename(__FILE__), 'line' => __LINE__]); // ファイル名(フルパス)
$this->monolog->info('ログメッセージ', ['file' => basename(__FILE__), 'line' => __LINE__]); // ファイル名のみ
ログファイルに記録 + メール送信
$this->monolog->error('5. error');
$this->monolog->critical('6. critical');
$this->monolog->alert('7. alert');
$this->monolog->emergency('8. emergency');