Yii2 custom logger

Step 1:
app/config/console.php

 
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'app\helpers\MyFileTarget',
                    'exportInterval' => 1,
                    'categories' => ['my-category'],
                    'except' => ['application'],
                    'levels' => ['trace'],
                    'logFile' => '@app/runtime/logs/my-category.log',
                ],
            ],
        ],

Step 2:
Create file app/helpers/MyFileTarget.php

 
<?php
 
namespace app\helpers;
 
use Yii;
use yii\log\Logger;
use yii\log\FileTarget;
 
class MyFileTarget extends FileTarget
{
 
    public function formatMessage($message)
    {
        list($text, $level, $category, $timestamp) = $message;
        $level = Logger::getLevelName($level);
 
        if ($level == 'trace') {
        return date('Y-m-d H:i:s', $timestamp) . " [$level][$category] $text";
        }
    }
}

Step 3:

cat /var/www/yii2-installed-dir/app/runtime/logs/my-category.log

Leave a Reply