Colorado Timberline APIA Practical Guide to Successful Integration

PHP Logging System

Overview

The CtApi core library has several classes which may have relevant information to disseminate at runtime, but Ct has no idea what you want to do with that information (if anything) or where to put it etc.

This is why Ct provides a simple default behavior of echo’ing log messages from the core library based on a moderate priority level of INFO. Not only can you tailor the amount of output by simply updating your config/envs.php file, you can totally customize the logging implementation.

Why would I write my own?

  • You want to change the target of the log messages. If you’re running the code through a webserver, likely echo statements won’t be a very effective tool to capture important output from the library, which is also true if you’re running the code from cron jobs.
  • You want to change the conditions under which log messages are considered. All the logic to determine how to handle a log message is in the implementation of the log handler; you can even ignore the priority information supplied by the client code if you wish.

Implementing a log handler

The interface to the logging mechanism is a single function taking a message and a log level as input. You can provide this as a php pseudo-type callback for the CtLogHandler field in your config/envs.php file.

Handler API

void function(string $message, int $logPriority)

Example log handler specification

Class MyLogHandler provides static method handle

config/envs.php
$a_ct_envs = array(
// ct hosted, non-live environment
'staging' => array(
// ...
'mLogHander' => array('MyLogHandler', 'handle'),    // implement a custom log handler
),

Since any valid callback is allowed, global functions will work as well

Global Library Function
function handleCtApiLogMsg($sMsg, $iLevel)
{
// syslog all messages to a common infrastructure via UDP ;)
}
config/envs.php
$a_ct_envs = array(
// ct hosted, non-live environment
'staging' => array(
// ...
'mLogHander' => array('handleCtApiLogMsg'),    // implement a custom log handler
),

Objects can also be used, however it’s unlikely you’ll end up getting an object instance in config/envs.php. In order to use an object as a log handler, you’ll have to edit the configuration at runtime.

Implementing a log handler with an object
$aConfig = CtApiConfig::load('envs');
$aConfig['mLogHandler'] = array($oLogger, 'handle');
CtApiConfig::set('envs', $aConfig);

Example: The default implementation

<?php
/**
* Hook method to handle logging; default is to log everything less than or equal
* to the current log level, where log levels have the weights assigned to them as constant
* values on this class
*/

static public function _handle($sMsg, $iLevel)
{
    $aConfig = CtApiConfig::load('envs');
    $iConfig = array_search($aConfig['sLogLevel'], self::$_aLogLevelMap);
    if($iConfig <= self::INFO)
        echo $sMsg . PHP_EOL;
}