Custom File Logging in Symfony for Cron Jobs or More

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!
Tags:

About marc

a Senior Software Engineer in Los Angeles, CA. He likes to receive comments :)