How to Configure Monolog to Email Errors

How to Configure Monolog to Email Errors

Monolog can be configured to send an email when an error occurs with an application. The configuration for this requires a few nested handlers in order to avoid receiving too many emails. This configuration looks complicated at first but each handler is fairly straightforward when it is broken down.

The mail handler is a fingers_crossed handler which means that it is only triggered when the action level, in this case critical is reached. The critical level is only triggered for 5xx HTTP code errors. If this level is reached once, the fingers_crossed handler will log all messages regardless of their level. The handler setting means that the output is then passed onto the buffered handler.


If you want both 400 level and 500 level errors to trigger an email, set the action_level to error instead of critical. See the code above for an example.

The buffered handler simply keeps all the messages for a request and then passes them onto the nested handler in one go. If you do not use this handler then each message will be emailed separately. This is then passed to the swift handler. This is the handler that actually deals with emailing you the error. The settings for this are straightforward, the to and from addresses and the subject.

You can combine these handlers with other handlers so that the errors still get logged on the server as well as the emails being sent:

This uses the group handler to send the messages to the two group members, the buffered and the stream handlers. The messages will now be both written to the log file and emailed.

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License .