Home

    More Logging

    Have been refining my policy on modular logging that I started here to give it a more OO based approach.

    The key thing is that it still checks isset() before calling so the code will run fine without any logger being configured. As most of the time the debugging code is only relevant to the developer of the module anyway the end user will rarely need to do anything and the code runs with minimal overheads, however it is simple to turn on debugging on a module by module basis if required.

    class MyTestModule {
      public static $logger;
     
      public function myRoutine() {
        ...
        isset(self::$logger) && self::$logger->log('info', 'My Message');
      }
    }

    Of course this is the point at which it would be really handy if SPL included an interface for SPL_Logger but even without that it is fairly trivial to wrap whatever logger you are actually using based on the interface provided.

    Here is the interface I use in my projects

    interface Standard_Logger {
      /**
      * A standard logging interface
      * @param  string  $level    One of 'error', 'warn', 'info', 'debug'
      * @param  string  $message  The message to write
      */
      public function log($level, $message);
    }

    And here is an example of hooking it up to a framework or application.

    /**
    * An example mapper to Kohana v3 logging
    */
    class Kohana_Standard_Logger implements Standard_Logger {
      public function log($message) { Kohana::log->add($level, $message); }
    }
     
    class MyApplication {
      public static function run() {
        // turn on logging for the class
        MyTestModule::logger=new Kohana_Standard_Logger();
        MyTestModule->myRoutine();
      }
    }