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.