I am writing my own logging class to save data in a DB. As I looked how CI is doing I noticed there is a log_message()
function which handles the logging. There is
Short answer: You can write your own log class to override the default CI class:
<?php
// this file is /application/libraries/MY_Log.php
class MY_Log extends CI_Log {
public function write_log($level = 'error', $msg, $php_error = FALSE)
{
// Put your own logging function in here.
// If you want it to still log to a file as usual, use this:
parent::write_log($level, $msg, $php_error);
}
}
Long answer:
The load_class()
function is basically a singleton loader. If the class has already been loaded, return a previous instance; otherwise, load it and create the singleton. It is very important in a framework like CI. You have to know that every time you call, say, a database function, it is applying it to the same object, not instantiating a new one (that would get really messy). All CI libraries function this way by default.
An important note: they changed how this functions significantly in version 2.0. Previously, it would only load from the /libraries
folder, but now, it will load from /core
or wherever you specify when calling the function.
Here's the process for loading, say, the Log class (from your example):
$_log =& load_class('Log');
$_log->write_log($level, $message, $php_error);
This runs the following checks, in sequence:
/system/libraries
folder for a "Log.php" file/application/libraries
for a "MY_Log.php" file (or whatever your subclass prefix is set to in your configuration)/system
folder), but you DO have an extended class under /application
, load that class too.I've actually never needed to use the load_class()
function, as it allows extension fairly seamlessly. However, it's good to know how it works.
So, to override a class, first find where the original resides (usually /system/libraries
or /system/core
). Put your extending file in the corresponding /application
folder (this is important! If it's under /system/core
, the extension MUST be under /application/core
). Prefix both the filename and the class name with MY_
(or whatever you set in your configuration), and have it extend the CI_
base class.