Innam Hunzai
Innam Hunzai

Reputation: 462

How to set logFile path dynamically for different modules in yii

I want to set different logpath for each module so that all errors, warnings, should be categorize with module name as parent folder.

i.e

runtime/logs/module_name/errors.log

runtime/logs/module_name/warnings.log

runtime/logs/module_name/info.log.

currently log component is configured in config/main.php

    'log' => [
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'flushInterval' => 1,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['info'],
                'categories' => ['common\modules\*'],
                'logFile' => '@runtime/logs/common.modules.info.log',  
            ],
      ],
]

I want to dynamically assign logFile path value in above application configuration file, so that if any error, warning, info is called in any module it will automatically pick that module name and logs the information.

Upvotes: 2

Views: 1502

Answers (1)

Egor Dudin
Egor Dudin

Reputation: 1

You can add log target dynamically from controller or module init.

$target = new FileTarget();
$target->logFile = \Yii::getAlias('@runtime') . '/custom.log'
$target->categories = ['log-category']
\Yii::$app->getLog()->targets = [$target];

But I think will be better create new FileTarget class and moved static settings like categories into it.

Upvotes: 0

Related Questions