我想用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
你可能會很好地在那裏。 –