Write to a log file with PHP

More...

As you certainly know, PHP can be used for command line scripting. In my case, I caught myself writing log PHP function many times so I finally decided to write Logging PHP class. After Logging class initialization, first call of lwrite method will open log file for writing. If lclose method is not called at the end, then log file will be closed implicitly.

Before you read further, I also wrote a post how to Log PHP errors to the separate file, if you are looking for such information.

How to use Logging class:

// Logging class initialization
$log = new Logging();

// set path and name of log file (optional)
$log->lfile('/tmp/mylog.log');

// write message to the log file
$log->lwrite('Test message1');
$log->lwrite('Test message2');
$log->lwrite('Test message3');

// close log file
$log->lclose();

Logging class source code:

/**
 * Logging class:
 * - contains lfile, lopen, lclose and lwrite methods
 * - lfile sets path and name of log file
 * - lwrite will write message to the log file
 * - lclose closes log file
 * - first call of the lwrite will open log file implicitly
 * - message is written with the following format: hh:mm:ss (script name) message
 */
class Logging{
    // define default log file
    private $log_file = '/tmp/logfile.log';
    // define file pointer
    private $fp = null;
    // set log file (path and name)
    public function lfile($path) {
        $this->log_file = $path;
    }
    // write message to the log file
    public function lwrite($message) {
        // if file pointer doesn't exist, then open log file
        if (!$this->fp) {
            $this->lopen();
        }
        // define script name
        $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
        // define current time
        $time = date('H:i:s');
        // write current time, script name and message to the log file
        // in case of using on Windows, instead of "\n" use "\r\n"
        fwrite($this->fp, "$time ($script_name) $message\n");
    }
    // close log file (it's always a good idea to close a file when you're done with it)
    public function lclose() {
        fclose($this->fp);
    }
    // open log file
    private function lopen() {
        // define log file path and name
        $lfile = $this->log_file;
        // define the current date (it will be appended to the log file name)
        $today = date('Y-m-d');
        // open log file for writing only; place the file pointer at the end of the file
        // if the file does not exist, attempt to create it
        $this->fp = fopen($lfile . '_' . $today, 'a') or exit("Can't open $lfile!");
    }
}

For PHP prior to version 5.2.0 you will have to replace or change line with built-in PHP function pathinfo() because PATHINFO_FILENAME constant was added in PHP 5.2.0

// for PHP 5.2.0+
$script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

// for PHP before version 5.2.0
$script_name = basename($_SERVER['PHP_SELF']);
$script_name = substr($script_name, 0, -4); // php extension and dot are not needed

If you want to send a message to the PHP's system logger, please see the error_log PHP command.

This entry was posted on January 14, 2009 and is filed under PHP

Related posts

25 Responses to Write to a log file with PHP

  1. bhowe says:

    Shouldn't you always implicitly close file handles or am I just paranoid ( or blind) . Nice little class though Ill add it to my arsenal.

  2. Mathou says:

    Nice, Thanks.

  3. devidas says:

    This is nice code I was implement in my project. Thanx so much

  4. Kay says:

    Very useful, but would give better output for windows with each message on a new line by adding " /r" in the fwrite() function. that is:

    fwrite($this->fp, "$time ($script_name) $message\r\n");
    

    EXAMPLE OUTPUT:

    16:03:15 (preview) Test message
    16:03:35 (preview) Test message
    16:03:50 (preview) Test message
    

    I used it thanks

  5. dbunic says:

    @bhowe - Logging class now contains lclose public method - thank you.

    @Kay - You are right. If Logging class is used on Windows then CR and LF shoud be used to break the line. Linux/Unix uses only LF. I added "\r\n" to the comment above fwrite line.

    Info: From this moment, source code of the Logging class can be downloaded from the Download link below post title.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>