create custom logging in codeigniter

Rakesh Sharma      No Comments  

How to create custom logging in codeigniter by extending codeigniter logging system

We already have default beautiful logging system in codeigniter. Which are really more helpful, I am just extending the logging system for showing custom log message in codeigniter.

Default codeigniter logging we can see in application/config.php.

/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
|	0 = Disables logging, Error logging TURNED OFF
|	1 = Error Messages (including PHP errors)
|	2 = Debug Messages
|	3 = Informational Messages
|	4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| 	array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 1;

If you get any error in code you will get error in log file like below.

ERROR - 2016-03-09 11:03:08 --> Severity: error --> Exception: Unable to locate the model you have specified: Accountmodel /var/www/html/mysite/system/core/Loader.php 314

But if i don’t want to show log message with in ERROR part. I need to create custom logging in codeigniter. Let’s see how we can create our own logging in codeigniter including default logging system.

Step 1 : Define log_threshold value as an array. I added 5 for custom logging.

$config['log_threshold'] = array(1, 5);
// here 5 is stand for custom logging.

Step 2. 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);

and add your custom level to array to extend log message.

/**
 * Predefined logging levels
 *
 * @var array
 */
protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4, 'CUSTOM' => 5);
// custom is our message part to show logging.

Step 3. Now create custom logging using codeigniter log_message($level, $message) function. Use $level as we have custom defined.

if ($some_var == 'mine')
{
    log_message('custom', "\n------------ My var value is -----------\n".$some_var);
}

Now you will seen in log.php your custom message or logging is writing in seperate part with level we have defined like

create-custom-logging-in-codeigniter

So now you can use log_message() function to create your own custom logging in codeigniter using your custom level.