Custom log to file function with log rotation and log levels

I often need logging in my applications so instead of inventing the wheel every time I decided to write a reusable log function. This is what I came up with (PHP 5.3.3)

/**
 * Log function with log file rotation
 * and loglevel restrictions
 *
 * @param <int> $level
 * @param <string> $event
 * @param <string> $text
 */
function logger($level, $event, $text = null){
        $maxsize = 5242880; //Max filesize in bytes (e.q. 5MB)
        $dir = "log/";
        $filename = "myapplication.log";
        $loglevel = 5;

        if(file_exists($dir.$filename) &&
                  filesize($dir.$filename) > $maxsize){
            $nb = 1;
            $logfiles = scandir($dir);
            foreach ($logfiles as $file) {                
                $tmpnb = substr($file, strlen($filename));
                if($nb < $tmpnb){
                    $nb = $tmpnb;
                }
            }
            rename($dir.$filename, $dir.$filename.($nb + 1));
        }
        if($level <= $loglevel) { 
           $data = date('Y-m-d H:i:s')." LEVEL: ".$level." ";
           $data .= "EVENT: ".$event." ".$text.PHP_EOL;
           file_put_contents($dir.$filename, $data, FILE_APPEND);
        }
}

This function will write a log row with a timestamp, error level, event name and error text (optional) to the logfile specified if the error level is below or equal to the general log level ($loglevel). If the logfile is bigger then $maxsize it vill rename the logfile by appending the next inline number to the end and create a new logfile.

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.