Blogs | Srijan

Fundamentals of Drupal Monolog Module

Written by Samiksha Gupta | Sep 7, 2020 7:00:00 AM

In a typical scenario of staging or production, developers seldom have the option to use the debugger so they turn to the logging functionality to resolve system issues.

One of the most underutilized tools at the developer’s disposal, ideally, logs should be the first thing that developers should look at when trying to resolve a system error or spending time tracking down a gnarly bug.

This blog will walk you through the Drupal module, Monolog, that logs the messages of the site (words, errors, notices, & warnings) in the file to fix issues swiftly without impacting the site performance. Find out how it can be installed and how it works.

The ABC of Monolog Module

In a typical scenario, a module trying to log the debug information in the database table has to connect to the database every time, making the whole process tedious. Additionally, the gradual increase in table size starts hampering the site performance.

Contrary to this, another way of logging the site messages without impacting the site performance is by saving these messages in the file. Whenever the site will be down due to fatal errors, the messages can be checked from the log file.

Monolog is one of the modules in Drupal that saves messages (words, errors, notices, warnings) in the file to save the system from the overhead of buffering logs and network errors.

 

 The Monolog module integrates Drupal with the Monolog library to offer a better logging solution. It can send logs to files, sockets,   inboxes, databases, and various web services. In a nutshell, it allows you to define a logging pipeline. 

 

 When it logs something, it dispatches it along that pipeline to whichever files, services, emails, etc. you have defined.

Benefits of Monolog Module

It offers the following benefits

  • Enhanced system performance

Monolog logs system messages as per the defined file system/structure, thereby enhancing the overall performance of the application and system.

  • A multitude of handlers

The multiple handlers defined in monolog can be integrated hassle-free to send log messages into an email, Slack, etc.

  • Easy to install

The Monolog module is easy to install as it does not require any external library and server for configurations

  • Complete watchdog integration

The Monolog module consists of full watchdog integration, making it easier to work with core and contributed modules out of the box.

  • Configurable logging levels

The Monolog module is PSR-3  (PHP Standards Recommendation). As a result of which, it enables interoperability to help you change the logging library for another that implements PSR-3 without too much headache.

Why is Monolog Important?

Drupal core logging offers minimal features to developers for defining a log message type, “attention level,” and then saving all the log messages to a destination, usually Syslog; even when the logging can be redirected to another destination. All the log messages, including those where critical problems are listed, are stored at the same place with trivial logged information.

Whenever the site encounters an unexpected issue, site owners try to find the cause behind it. Though all the information is written to the log system by Drupal, it quickly gets overwritten with newer log messages on an active site. Once it happens, it becomes difficult to recover because they all stay in the same log stream along with PHP errors and warnings and all the other types of system logs.

This is why the Monolog module comes in handy. With it, you can send critical logs to email, HipChat, or NewRelic, normal logs to a persistent backend, and debug to a simple pre-defined log file.

The clear separation of information by concerns extensively improves access to the specific log information that is relevant and useful in any given situation. 

In fact, you can use this module to write operational logs related to the content and user actions to a particular stream so the site owner can gain access to that information instantly without going through all the unnecessary or irrelevant log messages.

At the same time, a system administrator can see all system logs on a different stream, and receive critical messages only via email.

How to Install the Monolog Module?

The monolog module can be installed by using the composer.

The Monolog module does not have any configuration form in the backend, and all the configuration is done in services files. You can follow the below-mentioned steps for the same-

  1. Create a site specific services.yml (monolog.services.yml, for example) in the same folder of your settings.php and then add this line to settings.php itself:
$settings['container_yamls'][] = 'sites/default/monolog.services.yml';
 
2.   The simplest configuration that allows Monolog to log to a rotating file could be-

 

parameters:
monolog.channel_handlers:
default: ['rotating_file']
monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referer']

services:
monolog.handler.rotating_file:
class: Monolog\Handler\RotatingFileHandler
arguments: ['private://logs/debug.log', 10, 'monolog.level.debug']

3.  This configuration will log every message with a log level greater (or equal) than debug to a file called debug.log located into the logs folder in your private file system. Since data will be rotated every day, the maximum number of files that you can keep would be 10.

Role of Handlers & Processors in Monolog’s Functionality

Handlers are accountable for saving the message to the file, database, or sending it to a mail. In Drupal Monolog’s default monolog.services.yml, several handlers are defined, for instance, monolog.handler.browser_console, monolog.handler.chrome_php, monolog.handler.fire_php, etc. These are registered as services in the Drupal Service Container. You can define as many handlers as you need. Each handler has a name (that should be under the monolog.handler. namespace), an implementing class, and a list of arguments. 

Mapping among logger channels and Monolog handlers is done by defining parameters. Under the monolog.channel_handlers parameter, it is possible to determine where to send logs from a specific channel. The default mapping should exist as the fallback one. In the previous example, all logs were sent to the monolog.handler.rotating_file handler. 

Note -  Only the handler name is used instead of the full-service name.

The following example will send all PHP specific logs to a separate file:

parameters:
monolog.channel_handlers:
default: ['rotating_file']
monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referer']

services:
monolog.handler.rotating_file:
class: Monolog\Handler\RotatingFileHandler
arguments: ['private://logs/debug.log', 10, 'monolog.level.debug']

It method will write the corresponding message to the private://logs/php.log file.

On the other hand, a processor is a PHP callable used to process the log message-

monolog.processors: ['message_placeholder', 'current_user', 'request_uri', 'ip', 'referrer']
 

Monolog can alter the messages being written to a logging facility using processors. The module provides a set of already defined processors to add information like the current user, the request URI, the client IP, and so on.

Processors are defined as services under the monolog. processor. namespace. We can also use the Devel module or Drupal Console to find all of them.

'Message_placeholder': text of message

'Current_user' : logged in user

'Request_uri' : requested url

'Ip' : ip address of user

‘'Referer': url from where the user has arrived to the page.

How to log custom messages in a custom module using Monolog? 

To log custom messages, add the below-mentioned code in your custom module-

\Drupal::logger('php')->debug('debug message');
 

It will successfully write the corresponding message to the private://logs/debug.log file.

E.g 

\Drupal::logger('php')->debug('Data added using cron');

 

Conclusion

The Monolog module offers complete flexibility to help you capture the right information and leverage it for troubleshooting and monitoring. Once you have configured your applications to log all the useful information, you can send these logs to a platform where it can be used for in-depth analysis and collaborative troubleshooting.

Install the module for speedy development and resolve errors hassle-free.