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.

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.

About Matthias

Avatar von Matthias Pigulla

Matthias Pigulla

Diplom-Wirtschaftsinformatiker, Geschäftsführer

Der strategische Kopf hinter unseren Softwaresystemen behält bei der Entwicklung und Betreuung komplexer Architekturen den Überblick, kümmert sich um die technische Infrastruktur oder berichtet über seine Erfahrungen und Erkenntnisse auf der Symfony User Group. Und wenn er abends damit fertig ist, entspannt der zweifache Vater entweder auf seiner Yogamatte oder lässt beim Fotografieren die Seele baumeln.

Was this helpful for you? Let @webfactory or @mpdude_de know!

Wir suchen Symfony-Entwickler*innen!

To top