Symfony

Using Monolog to provide console output in Symfony 2.4

As of Symfony 2.4, console applications can intercept messages sent to a Monolog\Logger and display them on the console. Thus, your domain logic need only deal with an implementation of the Logger interface and send it the messages suitable for tracing program execution.

Written by: Matthias
Published on: 2013-11-08

This code can then be run in web or console environments and the messages be routed as appropriate - to the console, a log file or both.

At the heart of this new feature is ConsoleHandler, a straightforward implementation of the Monolog HandlerInterface. The feature announcement including the design rationale and possible customizations can be found over in the Symfony2 blog.

Creating the ConsoleHandler instance directly

There's one little thing that might bite you if you follow the directions in that article, though.

The config.yml and related configuration files are under control of the "app" developer who ties his own ("src") and other people's ("vendor") code together.

So if you're providing a console command as part of a distributed bundle, chances are that your end user might forget to include the ConsoleHandler as part of the logging setup which might lead to console commands with little or no useful output.

One way to address this is to push the ConsoleHandler to the appropriate Logger(s) yourself during the initialization of your Command, like so:

How to extend this example to subscribe to several loggers or changing the formatting is left to you as an exercise :-). When unsure on how to do this, our recent posting about Monolog and Symfony2 might also help.

Erfahren Sie mehr über unsere Leistungen als Symfony Agentur.

Did we spark your interest?

If so, we'd love to hear from you. Don't hesitate to get in touch with us, if you have any questions or further remarks. And if you want to discuss any type of project, product, problem or idea with us, we would like to even more!

Contact