我想用PHP写/读滚动日志文件,其中只有最新的〜300行被存储/读取,并且任何旧版本都被丢弃。我不确定最有效的方式 - 它需要在高流量网站上记录页面访问时快速工作。PHP中的滚动日志文件
另一个PHP脚本将定期读取日志文件并使用数据进行计算。有很多PHP文件函数让我困惑,从哪里开始!
我不认为我的托管环境可以访问诸如tail
或awk
或类似命令,因此纯PHP解决方案是首选。任何帮助感谢!
我想用PHP写/读滚动日志文件,其中只有最新的〜300行被存储/读取,并且任何旧版本都被丢弃。我不确定最有效的方式 - 它需要在高流量网站上记录页面访问时快速工作。PHP中的滚动日志文件
另一个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);
接下来泵文件到一个数组和LOB关闭所有除最后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脚本会读取它吗? –
@fireeyedboy我认为一个文件的写入速度会比数据库快,而且一点研究似乎都认同。我真的只是想要数据输入和数据输出,所以我认为一个数据库是过量的 – Tak
你可能会很好地在那里。 –