Send user ID with Email log

I always send logs on developer email for developers to look at exceptions that occurs in the system and fix the issue. However sometimes we need to know which user is experiencing the issue. With that, we need user ID. Have anyone have experience with this one? I cannot find a way to send it with log email.

Here is how I do it (sends logs but with no user identity details)

$config['components']['log'] = [
    'traceLevel' => 3,
    'targets' => [
        [
            'class' => 'yii\log\EmailTarget',
            'mailer' => 'mailer',
            'levels' => ['error', 'warning'],
            'message' => [
                'from' => ['someemail@example.com'],
                'to' => ['problems@example.com'],
                'subject' => Yii::t('app', 'Logs for {date} by {name} - {uid}', [
                    'date' => date('d-m-Y'),
                    'uid' => Yii::$app->user->id ?? 'NONE',
                    'name' => Yii::$app->user->identity->name ?? 'NONE',
                ]),
            ],
        ],
    ],
];

I get None for UID and Name
I will appreciate any idea

It’s to early to get the value in config.
I don’t know but try to use the prefix property of the log target.

https://www.yiiframework.com/doc/api/2.0/yii-log-emailtarget#$prefix-detail

1 Like

exactly what I needed thank you!
For anyone thnking of doing the same here is a working sample

$config['components']['log'] = [
    'traceLevel' => 3,
    'targets' => [
        [
            'class' => 'yii\log\EmailTarget',
            'mailer' => 'mailer',
            'levels' => ['error', 'warning'],'prefix' => function($message){
                return Yii::t('app', 'Details: Date - {date} Logged In - ({name} - {uid})', [
                    'date' => date('d-m-Y'),
                    'uid' => Yii::$app->user->id ?? 'NONE',
                    'name' => Yii::$app->user->identity->name ?? 'NONE',
                ]);
            },
            'message' => [
                'from' => ['someemail@example.com'],
                'to' => ['problems@example.com'],
                'subject' => Yii::t('app', 'Logs for {date} by {name} - {uid}', [
                    'date' => date('d-m-Y'),
                    'uid' => Yii::$app->user->id ?? 'NONE',
                    'name' => Yii::$app->user->identity->name ?? 'NONE',
                ]),
            ],
        ],
    ],
];
1 Like