Email log messages library in CodeIgniter

When working with CodeIgniter, I’ve found the log message functionality built into the framework very helpful. The other day I noticed in my log of one of my CodeIgniter based sites that I’ve had some 404 errors going on for some time. As I don’t have the time to check my logs daily, I hadn’t noticed this problem until now.

This led me to think that it would be real handy to get the log messages sent out by email as well, so you don’t risk to have a problem going on at the site unnoticed for days or even weeks.

So I wrote an extension to the native Log class in CodeIgniter which adds this functionality. Below is the code for MY_Log.php which extends the CI_Log class. MY_Log calls the native Log functions so the log file still gets generated, and if a log message was executed it also gets sent out by email afterward.

Change the email address in the code to the one you want to receive the log messages to, and then save the file in your application/libraries/ folder as MY_Log.php. This assumes that your Class Extension Prefix is set to MY_ in your config file.

I hope some of you find this class extension useful, and feel free to improve upon it. Cheers!

/**
 * MY_Log Class
 *
 * This library extends the native Log library.
 * It adds the function to have the log messages being emailed when they have
 * been outputted to the log file.
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Logging
 * @author      Johan Steen
 * @link        https://code.bitbebop.com/
 */
class MY_Log extends CI_Log {
    /**
     * Constructor
     *
     * @access  public
     */
    function MY_Log()
    {
        parent::CI_Log();
    }

    /**
     * Write Log File
     *
     * Calls the native write_log() method and then sends an email if a log
     * message was generated.
     *
     * @access  public
     * @param   string  the error level
     * @param   string  the error message
     * @param   bool    whether the error is a native PHP error
     * @return  bool
     */
    function write_log($level = 'error', $msg, $php_error = FALSE)
    {
        $result = parent::write_log($level, $msg, $php_error);

        if ($result == TRUE && strtoupper($level) == 'ERROR') {
            $message = "An error occurred: \n\n";
            $message .= $level.' - '.date($this->_date_fmt). ' --> '.$msg."\n";

            $to = 'someone@example.com';
            $subject = 'An error has occured';
            $headers = 'From: Example Name <no-reply@example.com>' . "\r\n";
            $headers .= 'Content-type: text/plain; charset=utf-8\r\n';

            mail($to, $subject, $message, $headers);
        }
        return $result;
    }
}