{"id":4490,"date":"2016-08-19T08:15:20","date_gmt":"2016-08-19T13:15:20","guid":{"rendered":"http:\/\/www.carnaghan.com\/?p=4490"},"modified":"2019-09-22T22:18:01","modified_gmt":"2019-09-23T02:18:01","slug":"logging-drupal-8","status":"publish","type":"post","link":"https:\/\/www.carnaghan.com\/logging-drupal-8\/","title":{"rendered":"Logging in Drupal 8"},"content":{"rendered":"\n
Logging is very important in any production site because we don’t have the same ability to debug code that we have in our development environments. Drupal<\/span> 7 had a very robust logging system called watchdog(), which has been replaced by logger in Drupal<\/span> 8. This post summarizes a basic use case for logging in<\/span> Drupal<\/span> 8 continuing the Drupal<\/span> 8 Activity Cards series on Day 13<\/a>.<\/p>\n\n\n\n Amber Matz breaks down logging in<\/span> Drupal<\/span> 8 concisely in How to Log Messages in Drupal 8<\/a>. In her article, she breaks down the code needed to implement logger and provides solid explanations. The examples provided involve procedural coding in the .module<\/span> file<\/span> as does the example I provide in this article. If you are writing controllers<\/span> or forms that extend ControllerBase or FormBase then it would be better to use the service container to inject logger into your code.<\/p>\n\n\n\n For a basic example, I created a custom module<\/span> that simply logged a message any time a node was updated<\/span>. In order to do this, I first referred to the available hooks in Drupal 8<\/a> and soon realized the best way to accomplish this would be through hook_entity_update<\/a>. To get started I issued the command<\/span>:<\/p>\n\n\n\n I provided the information requested and scaffolded out boilerplate code<\/span> for a new custom module<\/span> called Day 13. For more information on generating boilerplate code<\/span>, see Creating a Custom Content Entity Type<\/a>.<\/p>\n\n\n\n After the boilerplate code<\/span> was generated I edited the .module file<\/span> and implemented hook_entity_update.<\/p>\n\n\n\n To test, I enabled the new module and made a content update<\/span>. After reviewing logs<\/span> I found the new entry generated by the module.<\/p>\n\n\n\nBasic Example of Logging<\/span> Updates<\/h2>\n\n\n\n
drupal generate:module<\/pre>\n\n\n\n
Generated or updated files<\/span><\/span>\n Site path: \/var\/www\/drupal\/<\/span>drupal8<\/span>\n 1 - modules\/custom\/day13\/day13.info.yml<\/span>\n 2 - modules\/custom\/day13\/day13.module<\/span><\/pre>\n\n\n\n
function day13_entity_update(Drupal\\Core\\Entity\\EntityInterface $entity) {\n \\Drupal::logger('Node Updates')->notice('Node with title %title of type @type hs been updated',\n array(\n '@type' => $entity->bundle(),\n '%title' => $entity->label(),\n ));\n}<\/code><\/pre>\n\n\n\n