Skip to main content
You must unlearn what you have learned.

For the Record: Logging in Drupal 8

One of the most frustrating things about Drupal 8 is figuring out how to do things "the new way". watchdog() had been my faithful friend all through my development in D7. But, as famous Jedi once said, "You must unlearn what you have learned."

Out with the old …

In Drupal 8, watchdog() has been removed and replaced by a PSR-3 logging interface which is implemented as a Services. Out of the box, D8 comes with two such services; Database logging (dblog) and Syslog (syslog) which do exactly what they did in D7; send log messages to the database and system logs respectively.

When I first started learning (which by the way, I am still learning) Drupal 8, I thought this whole PSR-3 blah blah thing was going to be a PITA. Now, after taking the time to read the actual spec and finding a great article on Drupalize.me about D8 logging, my knee-jerk reaction to the changes were a waste of brain power and emotion. The new logging is just as easy to use as watchdog() ... if not easier!

"You must unlearn what you have learned."

– Jedi Master Yoda

Practice makes perfect

Taking what I learned in Amber Matz's article, I decided to refactor a custom module that I built to get my feet wet with the new Drupal 8 architecture; Astronomy Picture of the Day (apod), which adds a new block and page to display NASA's Astronomy Picture of the Day from their public web service. In the module, I created a Drupal service to connect to the REST API to retrieve the image details and cache it locally.

A logical place for logging in this module would in the actual API call itself so if the call failed, I would know why. Previously, I had just been setting error messages with drupal_set_message().

Excerpt from the original APODService::getImage() function:

      // Create a HTTP client.
      $client = \Drupal::httpClient();

      try {
        $response = $client->get(self::SERVICE_URL, $options);
      } catch ( RequestException $e ) {
        // @todo figure out what to do with the error.
        drupal_set_message($e->getMessage(), 'error');
        return FALSE;
      }

      if ( $response->getStatusCode() == 200 ) {
        $data = json_decode( $response->getBody() );
      } else {
        drupal_set_message('HTTP request resulted in a ' . $response->getStatusCode() . ' response.', 'warning');
        return FALSE;
      }
      
      $expire = $date->format('U') + self::ONE_DAY; // expire the cache in one day.

      \Drupal::cache()->set($cid, $data, $expire);

While this worked, the highlighted code was a less than desirable method of error reporting for a community module. The better way is to send the errors to the log so system administrators can see them and fix whatever is wrong.

Re-factored code using the D8 Logger:

      // Create a HTTP client.
      $client = \Drupal::httpClient();

      try {
        $response = $client->get(self::SERVICE_URL, $options);
      } catch ( RequestException $e ) {
        \Drupal::logger('apod')->alert($e->getMessage());
        return FALSE;
      }

      if ( $response->getStatusCode() == 200 ) {
        $data = json_decode( $response->getBody() );
      } else {
        $message = 'HTTP request resulted in a @status response; @body';
        $params = array(
          '@status' => $response->getStatusCode(),
          '@body' => $response->getReasonPhrase(),
        );
        \Drupal::logger('apod')->critical($message, $params);
        return FALSE;
      }
      
      $expire = $date->format('U') + self::ONE_DAY; // expire the cache in one day.

      \Drupal::cache()->set($cid, $data, $expire);

While there is slightly more code here, the resulting changes in the module have made the module more aesthetically pleasing to the user and more administrator friendly and closer to becoming something that I wouldn't be ashamed of putting on Drupal.org.

While refactoring apod, I another place where logging could be useful; setting the API key. System administrators may want to be notified if, when, and by whom any key changes are made. And because the new logging mechanism is easy to use, I just added that feature as I was writing this blog post! I could even write a custom logger that sends that specific notification to administrators via email! Maybe I'll tackle that in another post.

Change is not always bad

As you can see, although the changes in the Drupal architecture are significant, they are not a bad thing and do not necessarily mean things are more difficult; they are just different. There are lots of community resources to help you in your development journey. By taking the time to learn the new structures, you will be creating more reliable and stable code which ultimately makes you a better developer and the Drupal community will be beside you the entire way!

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.