我想用PHP编写/读取滚动日志文件,其中只存储/读取最新的~300行,丢弃任何旧行。我不确定最有效的方法 - 它需要快速工作,因为它在高流量网站上录制页面点击。
另一个PHP脚本将定期读取日志文件并使用数据进行计算。有这么多PHP文件函数我很困惑从哪里开始!
我不认为我的托管环境可以访问tail
或awk
等命令,因此首选纯PHP解决方案。任何帮助赞赏!
你可以使用fopen:http://us3.php.net/manual/en/function.fopen.php
$mode = 'a+'; // opens the file with read/write access and sets the pointer to the end of the file
$handle = fopen ($filename, $mode);
接下来,您将文件泵入一个数组并抛出除最后300行之外的所有内容。
如果你真的有兴趣将文件保持在一定的大小(你说〜300行),那么你可以使用fseek http://us3.php.net/manual/en/function.fseek.php(来自手册):
<?php
$fp = fopen('somefile.txt', 'r');
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);
?>
对于性能比较,您必须进行一些基准测试,但这是一种可能的方法:
<?php
function writeToLog($file, $str, $maxLines = 300) {
$linesToWrite = explode("\n", $str);
$numLinesToWrite = count($linesToWrite);
$logLines = explode("\n", file_get_contents($file));
array_splice($logLines,
$maxLines - $numLinesToWrite,
$numLinesToWrite,
$linesToWrite);
file_put_contents($file, implode("\n", $logLines));
}
不确定这个的表现,但这是我的看法:
// read lines in file as array
$lines = file( 'log.log', FILE_IGNORE_NEW_LINES );
// log file equal to or larger than 300 lines?
if( count( $lines ) >= 300 )
{
// remove everything from line 0 to 299 from the end
// in other words keep last 299 lines
array_splice( $lines, 0, -299 );
}
// append a new line of data
$lines[] = 'Test data ' . time() . "\n";
// put the lines back, first imploding the lines array with a newline char
file_put_contents( 'log.log', implode( "\n", $lines ) );
这样做的PHP功能。确保日志可写。如果不存在则创建日志:
// keeps log_file <= max_log_lines lines
function logTruncated($report, $log_file, $max_log_lines = 1000)
{
if (!$report || !$log_file)
return;
if (!touch($log_file))
die('Cant write log: '.$log_file);
$lines = array_merge(file($log_file), preg_split('/\r?\n/', $report));
$lines = array_slice($lines, -1 * $max_log_lines);
file_put_contents($log_file, implode("\n", $lines));
}