In Drupal 8 with DbLog logger, I am trying to log some audit messages to a different user than the currently logged-in user. Unfortunately, it looks like something is overwriting my context.

I tried \Drupal::logger("proreos")->info("bla", ['uid' => 5]); and \Drupal::logger("proreos")->info("bla", ['user' => User::load(5)]);, but neither of them worked. In both the cases, the current user ID was instead used.

How can I use a different user ID?

To clarify: This is not about logging another uid, it is about assigning the row in watchdog to a different user.


Logger will always log for the current user, except you provide your own logging service.

The context is used to replace placeholders in the message, see here, so to get the userid in the message, use this:

\Drupal::logger("proreos")->info("bla @uid", array('@uid' => 5));

The correct code is the following one.

\Drupal::logger("proreos")->info("bla %uid", ['%uid' => 5]);

This is similar to what Drupal does in user_cancel().

  if (!$account) {
    drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
    \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', array('%id' => $uid));

Consider the first and the second argument of error() or info() as the first two arguments of t().

  • 1
    The user ID in the watchdog table will still be of the current user. – Eyal Jun 15 '16 at 21:30

Thanks to you all. I appreciate that watchdog is not the correct table for my needs. I have created my own audit table and logging service now.

Your Answer

