As a developer you probably already know how important the concept of logging is. Logging greatly reduces the time it takes to debug defects which means you can spend more time developing fun stuff like new features. The following is a simple tip to assist in your debugging efforts.

According to symfony, you can access the logging framework through 1 of 3 of the following ways:

When inside an actions.class.php


$this->logMessage($level, $message);

// Example

$this->logMessage('err', 'Onoes something went wrong');

When inside a template:

<?php use_helper('Debug') ?>
<?php log_message($message, $level) ?>

// Example
<?php log_message('Ohnoes something went wrong', 'err') ?>

Anywhere else within Symfony:


sfContext::getInstance()->getLogger()->err($message);

// Example

sfContext::getInstance()->getLogger()->err('Ohnoes something went wrong');

You can create a unified API which can be called from anywhere, and has made my debugging life a little easier, consider the following:


// located @ /lib/MyCustom/Api/Log.php

class MyCustom_Api_Log
{
  /**
   * Wrapper method for getting a symfony logger object
   *
   * @return object
   */
  public static function getLogger()
  {
    return sfContext::getInstance()->getLogger();
  }

  /**
   * Wrapper method for logging debug message
   *
   * @param string $message
   */
  public static function logDebug($message)
  {
    self::getLogger()->debug($message);
  }

  /**
   * Wrapper method for logging an error
   *
   * @param string $message
   */
  public static function logError($message)
  {
    self::getLogger()->err($message);
  }

}

// Example Usage

MyCustom_Api_Log::logError('Ohnoes something went wrong');

Now, you can simply call this log wrapper class from anywhere within symfony and it will add an error level log message to the symfony log file.

One thing you may have noticed is the /lib/MyCustom directory, this will be explained in an upcoming post, but I have found that if you need to create classes that are not model related, putting them within in this directory keeps your /lib directory nice and clean and makes finding files much easier.