Skip to main content

Symfony and Monolog: define a custom logger file at runtime

Monolog

Monolog is a logging library. It is extremely powerful and most of the time only a tiny subset of its features are actually used. Just to mention a few extra features:

  • we can define different and complex logging strategies to keep only really interesting stuff
  • we can define to send our log to DB, to mail, to webservices
  • we can process the log record to add extra informations

Custom log

This time I had the need to write to a custom log file, but with the additional constraint that the file name was not known until runtime. That’s because the log is related to an import process which is generated as a new entity before being actualy executed.

On the Symfony Cookbook there is already a recipe about using different log files but it relies on a configuration made before the execution.

After a little experimenting, here’s the simple solution I implemented:

use Symfony\Bridge\Monolog\Logger;
use Monolog\Handler\StreamHandler;
// ...
$logger = new Logger('import');
$logger->pushHandler(new StreamHandler($kernelRootDir . '/logs/' . $runtimeGeneratedId.'.import.log', Logger::DEBUG));

As you can see, Monolog is not only powerful but easy to use, too!