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
March 22, 2009 at 3:31 pm
Hi Nicolas,
Just wondered whether a variation on the above is required for sf1.2 ?
I am currently getting “Fatal error: Call to a member function getRootDir() on a non-object” because of the line: file’ => $this->config->getRootDir().’/log/tasks.log’
Any ideas?
Thanks,
J
March 22, 2009 at 4:45 pm
In a task, the name of the configuration property is ‘configuration’, not ‘config’.
So try this instead :
$file_logger = new sfFileLogger($this->dispatcher, array(
‘file’ => $this->configuration->getRootDir().’/log/dostuff.log’
));
I fixed this typo error in the post.
June 11, 2009 at 8:12 pm
Hi,
Do you know if you can log in code called by a task?
My log statements are not printing out. It seems the context doesn’t get setup by the task.
Steve
June 11, 2009 at 8:56 pm
You can notify your log event from anywhere, using sfContext::getInstance()->getEventDispatcher()->notify()
Instead of creating the logger in the task, you can move it to your ProjectConfiguration::setup() method.
As this method comes early in the execution, the logger will be loaded and ready to be notified.
September 17, 2009 at 11:26 pm
Thanks…
This post helped me a lot ….