Topics Various subjects that interest me

Events Speaking/Visiting

Query monitor twig profile WordPress performance plugin

View the site on GitHub NielsdeBlaauw/actd.nl

Visit my GitHub Profile

Logging & handling exceptions

PHP & Monolog

Adding monolog as a dependency is easy with Composer:

niels@actd.nl:~$ composer require monolog/monolog

Setting up a basic logging solution is not much harder. The following code adds a new custom logger that outputs any events to a file on your server.

<?php
require_once('vendor/autoload.php');

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->info('Foo');
$log->error('Bar');

You can add different output channels in the form of handlers.

$log->pushHandler(new \Monolog\Handler\SlackWebhookHandler('https://slack.com/SECRET'));

There is a big list of available handlers that can output data on the Github repository.

To add metadata, like a URL, referrer, hostname, etc, you can add processors like the WebProcessor.

$log->pushProcessor( new \Monolog\Processor\WebProcessor() );

There are many processors available by default.

One additional handler that is particularly useful when working with WordPress is Wonologs WPContextProcessor. It logs some additional WP specific data, such as the multisite ID, the currently logged-in user and if the request was a CRON or AJAX request.

You can also format the output of the event. If you wanted to e-mail the alert, you might use the HtmlFormatter.

$handler->setFormatter( new \Monolog\Formatter\HtmlFormatter() );

It is possible to use handlers to control behaviour. The SamplingHandler allows you to only log every n-th message.

$stream_handler = new StreamHandler( 'path/to/your.log', Logger::INFO );
$sampling_handler = new SamplingHandler( $stream_handler, 10 ); // Only 1 in 10 messages goes to the stream handler.
$log->pushHandler( $handler );

The FingersCrossedHandler captures all events, until one exceeds some treshold level and then forwards everything to the next handler.

$stream_handler = new StreamHandler( 'path/to/your.log', Logger::INFO );
$handler = new FingersCrossedHandler( $stream_handler, Logger::ERROR );
$log->pushHandler( $handler );

To get a bit more background information you can watch the session ‘Advanced logging in PHP’ by Claes Gyllensvärd at DrupalCamp London.


You might also want to check out this in-depth article on monolog by stackify.

Plugins might provide their own logging and error handling. WooCommerce does logging like this:

wc_get_logger()->info('Foo');
wc_get_logger()->error('Bar');

While GravityForms provides a similar functionality:

GFCommon::log_debug('Foo');
GFCommon::log_error('Bar');

Centralised logging

There are platforms like Sentry that allow you to collect logging information in a central hub.


Javascript


Topics: