Write custom field in log table (yii\log\DbTarget)

Hello.
Is there some way to save custom fields into log table (besides level, category, etc) ?
I’m trying to save some errors to table, but one user should not see errors of another user. Is it possible to do somehow?

It is possible by implementing custom log target.

Did as below:
Copy file \yii\log\DbTarget.php to \app\components\DbTargetCustom.php
Changed namespace to

namespace app\components;

Renamed class as

class DbTargetCustom extends \yii\log\Target

changed some string on code:

...
$sql = "INSERT INTO $tableName ([[object_id]], [[owner_id]], [[level]], [[category]], [[log_time]], [[prefix]], [[message]])
                VALUES (:object, :owner, :level, :category, :log_time, :prefix, :message)";
...
$object = \Yii::$app->params['objectId'];
$owner = \Yii::$app->params['ownerId'];
...
if ($command->bindValues([
                    ':object ' => $object ,
                    ':owner' => $owner,
                    ':level' => $level,
                    ':category' => $category,
                    ':log_time' => $timestamp,
                    ':prefix' => $this->getMessagePrefix($message),
                    ':message' => $text,
                ])->execute() > 0) 
                continue;

And added new target to config:

‘targets’ => [
[
‘class’ => ‘app\components\DbTargetCustom’,

]

And now it saves object & owner in log table.

1 Like