问题
I have a function that keeps track of events that happen through out the script. In an effort to use my resources effectively, I decided to compress the data that it generates. However, I keep getting this error:
Unknown error type: [2] gzuncompress() [function.gzuncompress]: data error
Here's the function:
function eventlog($type, $message){
// Types: account,run,queue,system
// Set up file name/location
$eventfile = '/myprivatedirectory/'.date('Ymd').$type.'.log';
if(file_exists($eventfile)){
while(!is_writable($eventfile)){clearstatcache();}
$fh_log = fopen($eventfile,'r+');
flock($fh_log, LOCK_EX);
$logcontents = gzuncompress(fread($fh_log,filesize($eventfile)));
rewind($fh_log);
ftruncate($fh_log, 0);
$logcompressed = gzcompress($logcontents.$message."\n");
fwrite($fh_log,$logcompressed);
flock($fh_log, LOCK_UN);
fclose($fh_log);
} else {
$fh_log = fopen($eventfile,'w');
flock($fh_log, LOCK_EX);
$logcompressed = gzcompress($message."\n");
fwrite($fh_log,$logcompressed);
flock($fh_log, LOCK_UN);
fclose($fh_log);
}
}
So everyday, at midnight, a new error log is created as any of the above events occur (account,run,queue,system), otherwise each new event is appended to the respectful log file.
I would love to keep the compression, but I can not keep having these errors, can anyone please help? Thanks in advance.
回答1:
I think the implementation is all wrong i would not advice you to gzcompress($message."\n"); every message ...
I think what you should do is that at the end of the day you can compress the whole log file which is more efficient
Save your information using
file_put_contents
At the end of the day
$eventfile = '/myprivatedirectory/'.date('Ymd').$type.'.log';
$eventfileCompressed = '/myprivatedirectory/'.date('Ymd').$type.'.gz';
$gz = gzopen($eventfileCompressed ,"w9");
gzwrite($gz, file_get_contents($eventfile));
gzclose($gz);
To read the file
$zd = gzopen($eventfileCompressed,"r");
$zr = gzread($zd,$fileSize);
gzclose($zd);
This approach would save you more processing power
来源:https://stackoverflow.com/questions/9768237/php-gzuncompress-with-file-read-and-write-errors