Page 1 of 1

Error Logging Class

Posted: Thu Jul 27, 2006 4:32 am
by Benjamin
I've been putting off building an error log class for a while, but I really did need one so I wrote this. It's very simple but it's all I really need. Maybe this can go in snippets.

Code: Select all

// Sample windows path c:\\directory\\error_log.txt

class errorLogger
{
    function __construct($errorLog = '/server/projects/error_log.txt')
    {
        $this->log = @fopen($errorLog, 'a+b'); // open log

        if ((is_resource($this->log)) && (is_writable($errorLog)))
        {
            $this->ready = true;
        } else {
            $this->ready = false; // could not open file
            trigger_error("<b>The file " . $errorLog . " could not be opened or is not writable.</b>", E_USER_NOTICE);
        }
    }

    public function newEntry($entry)
    {
        if ($this->ready) fwrite($this->log, $entry . "\n");
    }

    public function clear()
    {
        if ($this->ready) ftruncate($this->log, 0);
    }

    function __destruct()
    {
        if ($this->ready) fclose($this->log); // close the file
    }
}
Call with..

Code: Select all

$errorLog = new errorLogger();

$errorLog->newEntry("This is test error"); // add entry

$errorLog->clear(); // delete log

Posted: Thu Jul 27, 2006 4:56 am
by jamiel
Put a timestamp with the error.

Posted: Thu Jul 27, 2006 12:08 pm
by daedalus__
you were write when you said simple.. :)

i wanted to have options. ^^

Posted: Thu Jul 27, 2006 7:54 pm
by Ambush Commander
Maybe a backtrace would be useful...

Posted: Thu Jul 27, 2006 8:09 pm
by Benjamin
Ambush Commander wrote:Maybe a backtrace would be useful...
Very good idea indeed!

Posted: Fri Jul 28, 2006 1:09 am
by daedalus__
Backtrace?

Posted: Fri Jul 28, 2006 1:13 am
by feyd

Posted: Fri Jul 28, 2006 6:29 am
by Jenk
as you are using PHP5, I cannot recommend strongly enough that you use exceptions. They are simply superb.

Perhaps a helper or wrapper class for your logger to use exceptions.

Code: Select all

class ExceptionLogger
{
    private $exception;
    private $logger;

    public function __construct ($errorLogger, $exception)
    {
        $this->logger = $errorLogger;
        $this->exception = $exception;
    }

    public function logError ()
    {
        $text = "Exception caught: " . get_class($this->exception)
              . "\nMessage: " . $this->exception->getMessage()
              . "\nTrace: " . $this->exception->getTraceAsString();

        $this->errorLogger->newEntry($text);
    }
}