Abraham Yusuf Abraham Yusuf - 5 months ago 172
PHP Question

How to maintain different log files for different purposes in Yii2

I am using Yii2 for a project. I have a class for consuming a third party service. This class has two methods sendRequest and processResponse. I would like to maintain separate logs for payload in sendRequest before actually sending it and another log for the raw response data received in processResponse before doing any processing. Additionally I would like log rotation on both logs as the files may grow indefinitely and want both files to be separate from the default app.log. Is this possible? How may I implement this using Yii2 APIs?

Answer

I eventually reverted back to using Yii2 logger by adding 2 additional file targets in my @app/config/main.php. The file targets had categories = ['orders'] and ['pushNotifications'] respectively so that in my code I use:

Yii::info($message, 'pushNotifications');

or

Yii::info($message, 'orders');

Here is my log config:

'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'targets' => [
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['error', 'warning'],
        ],
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['info'],
            'categories' => ['orders'],
            'logFile' => '@app/runtime/logs/Orders/requests.log',
            'maxFileSize' => 1024 * 2,
            'maxLogFiles' => 20,
        ],
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['info'],
            'categories' => ['pushNotifications'],
            'logFile' => '@app/runtime/logs/Orders/notification.log',
            'maxFileSize' => 1024 * 2,
            'maxLogFiles' => 50,
        ],
    ],
],
Comments