Posts Tagged ‘tasks’

Logging on tasks

Previously, I talked about creating a custom logging event in order to log into a another file .

This post shows how to add a task-specific logger.

About logging in tasks

In a Symfony task, two logging methods are available :

  • sfTask::log($messages)
  • sfTask::logSection($section, $message, $size = null, $style = ‘INFO’)

Both can be called anywhere in your task class :

class myownTask extends sfBaseTask
{
  ..
  protected function execute($arguments = array(), $options = array())
  {
    …
    $this->logSection(‘myTask‘, $myobject->getName().‘ is doing fine‘, 1000);
    $this->log(array($myobject->getName(), ‘is doing fine‘));
    …
  }
}

Theses two methods are in fact shortcuts to a notify command for the ‘command.log’ event :

$this->dispatcher->notify(new sfEvent($this, 'command.log', $messages));

the registred method for the ‘command.log’ event is an intance of the sfCommandLogger class. This logger simply display its content to the STDOUT. It is responsible for all the verbose messages that you see after launching a Symfony task.

Adding a file logger to your task

You can easily register a new logger to the existing ‘command.log’ event :

class dostuffTask extends sfBaseTask
{
  …
  protected function execute($arguments = array(), $options = array())
  {
    // Enable logging only with the –go command option is set
    if ($options['go'])

    {
      $file_logger = new sfFileLogger($this->dispatcher, array( 
        ’file=> $this->configuration->getRootDir()./log/dostuff.log‘
      ));
      $this->dispatcher->connect(‘command.log‘, array($file_logger, ‘listenToLogEvent‘));
    }
    …
  }
}

Now, any output message of the task by calling a log() method will also be logged into your file, if you set the –go option :

$ symfony mytasks:dostuff --go