在PHP中自动维护每日日志文件?

时间:2014-11-18 07:05:56

标签: php

我希望每天自动创建一个月的日志文件,之后将自动取消链接旧文件。以下是我的代码。我做得对吗如果是,那么有没有办法减少磁盘上的文件大小。

 $KeepDays = 30;  # how many days of log files we'll keep on hand
    $logname  = date("Ymd") . '.status.log';
    $OldFile  = date('Ymd',mktime(0,0,0,date("m"),(date("d") - ($KeepDays + 1)),date("Y"))) . '.status.log';
    if (file_exists($OldFile)) { unlink($OldFile); } # erase oldest log file 

    if (file_exists('logs/'.$logname)) {
        $fp=fopen('logs/'.$logname,'a');
    }else{
        $fp=fopen('logs/'.$logname,'w');
    }
    $chunk = "Var1_".$var1.'_'.$Var2.' var3_'.$var3.' var_'.$var.' var_'.$var4 ;
    fwrite($fp,$chunk. PHP_EOL);
    fclose($fp);

先谢谢。

1 个答案:

答案 0 :(得分:0)

不要以为它会去上班。您基本上删除旧文件,但不获取其内容。那些$ var1等定义了什么?有什么样的循环吗?

$KeepDays = 30;  # how many days of log files we'll keep on hand
$logname  = date("Ymd") . '.status.log';
// Would give '20141118.status.log ' for example

$OldFile  = date('Ymd',mktime(0,0,0,date("m"),(date("d") - ($KeepDays + 1)),date("Y"))) . '.status.log';
// Would give '20141018.status.log' for example

if (file_exists($OldFile)) { unlink($OldFile); } # erase oldest log file 
// Remove old file, but you remove it and can't get it's contents anymore. So you delete it wihtout copying its contents anywhere

if (file_exists('logs/'.$logname)) {
    $fp=fopen('logs/'.$logname,'a');
}else{
    $fp=fopen('logs/'.$logname,'w');
}
$chunk = "Var1_".$var1.'_'.$Var2.' var3_'.$var3.' var_'.$var.' var_'.$var4 ;
// Where are all those $var* defined? What you put here?


fwrite($fp,$chunk. PHP_EOL);
fclose($fp);

此外,您可以压缩或gzip文件的内容。