Logging app/user activity with custom (meta)data to database



I have a Yii2 application that should log important events such as start/end of a new business process (eg. "User x logged in.", "Order y completed."). These logs should be related to involved entities (models), eg. to the Order record of "Order y completed". I need that because in the final release the admin user should see a searchable table of logs with every entry being linked (related) to the involved records.

Thoughts so far:

I planned to have a "log" database table and a corresponding Log model to stores these logs.

Now I wonder how to trigger storing a log entry. I thought of implementing something myself, eg. simply creating a app\models\Log::log($message, $userId, $orderId, …) method - but it feels like bad practice.


That’s why I looked at Yii’s log methods - Yii::info($message, $category) etc.

But these methods only take 2 arguments, but I want a lot of metadata such as related records.

Should I pass an array with all metadata as the $message parameter and create custom yii\log\Target implementations that handle my custom format and save it to the database (using the Log model)?

What’s best practice to do such kind of logging in Yii?

Thank you very much!

Best, mrtn

The default log and the types of logging you want are two different types of logging. You are looking for audit logging and I’d personally use a custom model behavior for this. You can also look at a couple audit logging modules like https://cornernote.github.io/yii-audit-module/.