Logger library for Codeigniter

Codeigniter framework provides number of useful functions for Error Handling (described on http://ellislab.com/codeigniter/user-guide/general/errors.html). One of them – log_message(‘level’, ‘message’) writes a new log line to /application/logs/[log file name]. Great adventage of using this solution is that developer doesn’t have to create (open, close etc.) log files on filesystem. Just one function does the job.

Below you’ll find a code of Logger class that provides additional improvements to events logging. This class provides additional layer for logging proccess. It uses log_message(‘level’, ‘message’) for logging user – system interactions, and exceptions.

class Logger extends BaseLibrary {

    private $oUser;

    public function __construct() {
        parent::__construct();
        $this->oUser = $this->CI->sessionmanager->getUser();
    }

    /**
     * Logs action to log file as 'info'
     * Requires $config['log_threshold'] to be >= 3 (application/config/config.php)
     * @param string $strAction name of the action user takes
     * @param array $arrData optional details of taken action
     */
    public function logAction($strAction, array $arrData = null) {
        $strMessage = '';
        $strMessage .= 'action: ' . $strAction . ' ';
        $strMessage .= 'ip: ' . $this->CI->input->ip_address() . ' ';

        // add user id if any logged in
        if ($this->oUser->getId()) {
            $strMessage .= 'user: ' . $this->oUser->getId() . ' ';
        }

        // add data if provided
        if ($arrData) {
            $strMessage .= 'data: ' . str_replace(array("\n", "\r", "    "), '', print_r($arrData, true));
        }

        log_message('info', $strMessage);
    }

    /**
     * Logs exception to log file as 'error'
     * Requires $config['log_threshold'] to be >= 1 (application/config/config.php)
     * @param Exception $oException
     */
    public function logException(Exception $oException) {
        $strMessage = '';
        $strMessage .= $oException->getMessage() . ' ';
        $strMessage .= $oException->getCode() . ' ';
        $strMessage .= $oException->getFile() . ' ';
        $strMessage .= $oException->getLine();
        $strMessage .= "\n" .  $oException->getTraceAsString();
        
        log_message('error', $strMessage);
    }

}

BaseLibrary simply provides a refrence to the original CodeIgniter object:

class BaseLibrary {

    protected $CI;

    public function __construct() {
        $this->CI = & get_instance();
    }

}

Classes should be stored in /application/libraries. I recommend to auto load both of them.

Logger class provides logAction() method for logging user actions, and logException() for logging exceptions. Usage of logAction() is convinient for instance in CRUD models:

// within create() method
$this->logger->logAction('question created', (array) $this);

// within update() method
$this->logger->logAction('question updated', (array) $this);

// within delete() method
$this->logger->logAction('question deleted', (array) $this);

Just one line of code writes a fully detailed log, including: date/time, client ip address, id of logged user (if any), details array (i.e. model object dump). Example log line for object create() method:

INFO  - 2014-01-20 18:46:12 --> action: course created ip: 89.65.208.66 user: 2 data: Array([0] => Array([CoursecourseId] => 0[CoursecourseName] => Some name[CoursecourseName_dirty] => 1[CoursecourseQuestionsAmount] => [CoursecourseAveragePoints] => [CourseuserId] => 2))

Any array with details to be logged can be provided in the second parameter:

// custom example

$this->logger->logAction('wall painted', array('color' => 'green', 'foo' => $bar));

Leave a Reply

Your email address will not be published. Required fields are marked *