Custom logging in codeigniter

Default codeigniter provides a beautiful log library. But sometime we need to extend the log system. However codeigniter provides simplest way to do custom logging in many ways, This possible due to it’s flexible structure and build. In this article we will see how to create custom logging in codeigniter. Also you can find my previous article to integrate monolog in codeigniter.

Let’s see how we can add our own custom logging messages in codeigniter. We will make custom logging level so we can’t see many default/system messages in log file.

Predefined log level

If you check config.php there are some of predefined log levels. If we will use any of level’s we will see many of default messages generate by it’s default library.

/**
 * Predefined logging levels
 *
 * @var array
 */
protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4);

like if i use any of above log level’s with log_message(). Then i will see there are many of default messages appear in log file. If i want to make my separate log level and message then i need to make it using some customization.

log_message('info', "\n------------ My var value is -----------\n".$some_var);

Then you will see many information about system included in log file. So let’s see how we can make custom logging in codeigniter.

Codeigniter custom logging

1. Add custom log level

To add a level Go to system/core/log.php and search for below code.

/**
 * Predefined logging levels
 *
 * @var array
 */
protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4);

Then add your own custom log level in this array like below.

/**
 * Predefined logging levels
 *
 * @var array
 */
protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4, 'CUSTOM' => 5);

2. Define level in config

Now you need to define your log level in config file underlog_threshold like

$config['log_threshold'] = array(1, 5);

3. Write your own log message

Now you can write your custom logging messages using log_message() like

log_message('custom', "\n------------ My var value is -----------\n".$some_var);

Now you will see in log file log messages with own create custom log level. So you can create beautiful log messages without included predefined messages and a separate key with messages.

Cheerss! happy coding!

Adam Brown
Please follow and like us:

Leave a Comment