testing – How can I capture Watchdog output during a Drupal 8 functional test?

The Watchdog to File module is handy for this use case. You can initialize it in a test setup, like so:

<?php

namespace DrupalTestsmy_moduleFunctional;

use DrupalTestsBrowserTestBase;

/**
 * My browser tests.
 */
class MyBrowserTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->enableFileLogging();
  }

  /**
   * Enables logging of watchdog output.
   */
  protected function enableFileLogging() {
    $installer = Drupal::service('module_installer');

    // Enable logging ALL watchdog events to standard out.
    $installer->install((
      'watchdog_file',
    ));

    $config_factory = Drupal::configFactory();
    $config         = $config_factory->getEditable('watchdog_file.settings');

    $log_path =
      sprintf(
        '%s/artifacts/watchdog-%s.log',
        dirname(DRUPAL_ROOT),
        $this->databasePrefix
      );

    $config->set('log_filename', $log_path);
    $config->save(TRUE);
  }

}

Then, just configure GitLab CI to capture the test artifacts folder:

  artifacts:
    when: always
    reports:
      junit: artifacts/junit/*.xml
    paths:
      - artifacts/*
      - web/sites/simpletest/*

As a bonus, the above snippet also captures browser output produced by browser tests, in case you need to review them as well.

Each watchdog log should be named according to the Simple Test database ID that is used for the corresponding test run. For example, if you have five cases in your test, you should end up with five watchdog file logs.