Showing the User Agent in the Drupal 8 dblog

User Agent field in Drupal 8 Database Log

If you've just done a site restructure or migration to Drupal 8, you will inevitably need to redirect pages from your old URL scheme to however you've structured the new site.  In Drupal 8, the easiest way is to monitor the database log, filtered with "page not found".

Many of these hits however will come from bots scanning your site.  But to tell whether it's a random bot, Google, or likely to be a real user, we need to inspect the User-Agent header.  This means digging into your log files.  Wouldn't it be more convenient if you had a quick & easy way to see these details?

Here's a terribly hacky way to get the User-Agent to show in the details page of Drupal 8's database log.

  1. Add a field to store the User Agent.  In your MySQL database:
    ALTER TABLE `watchdog` ADD COLUMN `user_agent` VARCHAR(512) NULL AFTER `referer`
  2. Expose the User-Agent to all log channels. At Line 95 of core/lib/Drupal/Core/Logger/LoggerChannel.php (just below where the Referer is set), insert:
    $context['user_agent'] = $request->headers->get('User-Agent', '');
  3. Store the User-Agent in the database.  At line 81 of core/modules/dblog/src/Logger/DbLog.php (again, just below the Referer), insert:
    'user_agent' => $context['user_agent'],
  4. Display the field in the Event Details page.  At line 275 of core/modules/dblog/src/Controller/DbLogController.php (you guessed it, below Referer), insert:
            array(
              array('data' => $this->t('User Agent'), 'header' => TRUE),
              $dblog->user_agent,
            ),

Standard disclaimer applies.  This is an unofficial, unsupported hack.  There's probably a much more elegant way of achieving this by writing a Drupal 8 module.  But it works for me.  Don't use this on your production site.

Tags