How to best track impacted User when running console and service tasks

The Yii logging format is great for the frontend in that it automatically tracks the user in the userID field. Works great. However, in console commands and when sending work to a service layer or queue, e.g., yii2-queue, there is no “user”.

So for those jobs I have to take care to always add a line such as “USER=X” in the log output.

Is there a better way?

My thinking was that every service could simply Yii::$app->user->setIdentity($user). Is this standard practice or is this frowned upon?

It would completely solve the logging issue when running work through the console and service layer/queues/etc.

Any input on best practices or potential issues is appreciated!

Inc console app there is no logged user since there is no login at all.
Why do you want to have user? do you have audit fields (a la created_by and updated_by)?
In that case you can set them manually using special “console user” in your database.
Create user that is console user and set fields manually to that user id on the console action.

I have never tried login user in console. I expect it to be a challenge since by design console app does not expect to have user or session.

If you have time you want to check how codeception tests works in some tests

Hi Stefano, it helps with logging of errors, etc.

Also, you can use an identity in console via the user component. It works great. Check it out!

1 Like

You mean this?

Hi there,

You need to ensure you have identity config properly set in console/config/main.php as well. For example:

$config['components']['user'] = [
    'class' => 'yii\web\User',
    'identityClass' => 'common\models\User',
    'enableSession' => false,
    'enableAutoLogin' => false,

Once this is done, you are good to use Yii::$app->user->setIdentity() in console/non-web code in Yii2.