🍑

[PHP] Monologでログを取得する

2022/02/08に公開1

Monologでロギングするサンプルコード
Monolog1と2がありますが、2のほうになります

環境要件

  • PHP7.2以上
    → それ以下: PHP 5.3以上の場合は、Monolog1を使用のこと

事前準備

composer require monolog/monolog
# vendorディレクトリがDLされるので、移動させつつリネームする
mv ./vendor /usr/lib/monolog

コード

testLog.php
<?php

require_once('/usr/lib/monolog/autoload.php');

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;

// タイムゾーン設定
date_default_timezone_set("Asia/Tokyo");
// フォーマッタの作成
$dateFormat = "Y-m-d H:i:s";
$output = "[%datetime%] %channel% %level_name% %message%\n";
$formatter = new LineFormatter($output, $dateFormat);

// ハンドラの作成
$stream = new StreamHandler(__DIR__.'/log/test.log', Logger::INFO); // ログレベルINFO以上のみ出力
$stream->setFormatter($formatter);

// ロガーオブジェクトの作成
$logger = new Logger('test');
$logger->pushHandler($stream);

$logger->info('テスト'); // 出力される
$logger->debug('てすと'); // 出力されない
$logger->error('test'); // 出力される

実行結果

test.log
[2022-02-08 20:47:58] test INFO テスト
[2022-02-08 20:47:58] test ERROR test

参考

Discussion

andersenlab1andersenlab1

I'm so happy you have determined to use Monolog for your PHP application's logging needs! In my experience, Monolog is an absolute game-changer when it comes to logging in PHP. The flexibility it gives is unparalleled, and the ease of use is top-notch.
I should say, I'm a massive fan of the LineFormatter that you've got used to customise the log format. It's such a easy but effective function that can virtually make a distinction in how your logs seem to be and can be parsed.
If I might also humbly provide a suggestion, I'd advise thinking about a extra present day PHP model than 7.2. Newer variations of PHP have some splendid overall performance and safety enhancements that can honestly take your utility to the subsequent level. And, if you are searching for a extra current model of Monolog, you would possibly desire to test out the state-of-the-art model as nicely - it is acquired some super new elements and enhancements that you would possibly discover useful.
Overall, I suppose you have made an great preference with Monolog, and I'm certain your software will advantage extensively from it. If you have any in addition questions or want help with web development, experience free to reach out to us. https://andersenlab.com/services/web-development