Custom File Logging in Symfony for Cron Jobs or More

By marc • Apr 28th, 2008 • Category: Symfony

Have you ever needed to log your own information to a specific log file in symfony? Sure, the built in logging is very useful, but sometimes you just need to log some specific information to a file of your choice and don’t need a full stack trace. Today I needed to be able to do this when I was creating a batch file that would be run as a cron job. Basically I just wanted to log some information to a particular log file so that I could periodically check that it’s actually running and doing its thing.

Fortunately, this is simple from within symfony by directly accessing the sfFileLogger class. Here is an example of how you could log a message to your own log file.

  1.  
  2. // create our logger object
  3. $logger = new sfFileLogger();
  4.  
  5. // initialize the logger and set the file we want to log to
  6. $logger->initialize(array('file' => SF_ROOT_DIR . '/log/cron_status.log'));
  7.  
  8. // log the message!
  9. $logger->log("The cron job ran! Woohoo!", 0, "Info");

Looking at the sfFileLogger.class.php file it appears that the second argument of the log function isn’t used. So you can always set it to 0 as I have in my example above.

After running the example above, you will now see that you have a “cron_status.log” file in your SF_PROJECT/log directory containing something like the following:

  1.  
  2. Apr 28 14:51:30 symfony [Info] The cron job ran! Woohoo!

marc is a Web Developer in Los Angeles, CA. He likes to receive comments :)
All posts by marc

3 Responses »

  1. […] Ref: custom-file-logging-in-symfony-for-cron-jobs-or-more/ […]

  2. Hi Marc,

    As of right now this method of logging appears to not be working in symfony 1.1. You have to explicitly pass in EventDispatcher to get it to work.

    This version is working in 1.1:

    $logger = new sfFileLogger(sfContext::getInstance()->getEventDispatcher(), array(’file’=> ‘../log/cron_status.log’));

    $logger->log(”The cron job ran! Woohoo!”, 6);

    Note the difference in the log method also: 6 generates “info”.

    Cheers!
    -Jeff

  3. […] @ lampjunkie.com started on this one so most of the credit here goes to […]

Leave a Reply