log messages – Incorporating Drupal 8 logs into Splunk

In Drupal 8 you may define your own logger implementation to do whatever you want with log messages. The default logger provided by core Drupal saves these messages in the Drupal database and makes them available in the UI at /admin/reports/dblog. This default logger is implemented in the core dblog module by the logger class DrupaldblogLoggerDbLog, and that’s a great example to use when you write your own.

A logger is a class that implements LoggerInterface and is used as a service with the ‘logger’ service tag. All registered loggers are used for every channel. You don’t need to ‘trigger’ a logger or do anything special to have that logger automatically used by core Drupal, other than tagging the service.

The service definition for the core DbLog logger looks like this (from dblog.services.yml):

services:
  logger.dblog:
    class: DrupaldblogLoggerDbLog
    arguments: ('@database', '@logger.log_message_parser')
    tags:
      - { name: logger }
      - { name: backend_overridable }

You can see that the logger.dblog service is implemented by the DbLog class, and this service is tagged as a logger. That tag is how Drupal knows to send log message to this service. Without the tag, Drupal wouldn’t know this service was a destination for log messages.

Another good example in core is the core syslog module, which provides a logger that uses the PHP syslog() function to send messages to an operating-system-dependent location (probably a flat text file shared by all other programs that log messages on that operating system).

To make your own ‘Splunk’ logger, you would create a module that defines a logger service, for example logger.splunk. (Services are defined in the module’s <modulename>.services.yml file.) You must have a class, for example ‘Splunk’ that implements LoggerInterface. In that ‘Splunk’ class you may use the Splunk API to send log messages to Splunk. The details of how to do that is up to you as it has nothing to do with Drupal at this point. If you have code that sends log messages to Splunk from a standalone program then I think it is pretty clear from examples provided by core how to use that code in your logger class.

Your module will consist of a <modulename>.info.yml file, a <modulename>.services.yml file, and a <modulename>/src/Logger/Splunk.php file. Nothing more is needed. If you’ve done it right, then when you enable your module all messages should be logged to Splunk.