To make our application more elegant while working in cron, we should implement logging to a file. Symfony2 supports some standard logs, through the so-called monolog component. To use this, we simply call for the logger service, and then we call the required method, either the info, err, debug, notice methods or the warn method, as in the following example:

$logger = $this->getContainer()->get('logger');
$logger->info('Info log message');

This log message will add to the default log (development or production) depending on the environment.

We need to change this a little bit, to allow the logs to be added to a separate file.

To do this, we need to define the channel and handler. When we create a channel, a separate logger service is created, and we can use it to log information here. Creating a simple channel is easy, as we just need to pass its name into the channel’s array in the config file. After we add the channel, we need to add the handler, so that monolog would know what to do with the information logged in it.

Add the following code at the bottom of config.yml:

    channels: ['mail']
            # log all messages (since debug is the lowest level)
            level:    debug
            type:     stream
            path:     "%kernel.logs_dir%/mail.log"
            channels: [mail]

This code will add a single channel and handler to the file. Note the level of messages added. The debug level will guarantee that you will see every message. Next, we will define the type of the message, path where to store, and what channels are handled in it.

Now, when we have configured our custom logger, we can add them to our file to log the required information. To call the logger for our custom channel, we simply call a service with the name, monolog.logger.<channel>. In our case, add the following:

  // previously added code
  $em = $this

  // adding logger service
  $logger = $this

Now we can add our logging information to the following:

  foreach ($tasks as $task) { // previous code
      $output->writeln('Sending email to: '. $task['email']);
      // adding logger
      $logger->info('Sending email to: ' . $task['email']. 'with reminder about task: '. $task['id']);
      // ...

Add the following lines, too:

} catch (\Exception $e) {
    $output->writeln('<error>'. $e->getMessage() .'<error>');

Now, when the command sends an e-mail, it will be logged in a separate logger file.


If you want to test error logging, please make sure the spool: line in config.yml is commented out, otherwise swiftmailer will not return issues with e-mail sending directly after you call the send method.