如何解析PHP中的Apache错误日志?
时间:2020-03-06 14:59:41 来源:igfitidea点击:
我想创建一个脚本来解析或者理解apache的错误日志,以查看最新的错误是什么。我想知道外面是否有人这样做或者有什么想法从哪里开始?
解决方案
首先要考虑以下几件事:
- 首先,PHP用户可能无法访问Apache的日志文件。
- 其次,PHP和Apache不会告诉我们上述日志文件在哪里,
- 最后,Apache日志文件可能会变得很大。
但是,如果这些都不适用,则可以使用常规文件读取命令来执行此操作。
获取最后一个错误的最简单方法是
$contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES); if (is_array($contents)) { echo end($contents); } unset($contents);
可能有一种更好的方法可以不占用内存,但我将其留给读者练习。
最后一句话:PHP还具有ini设置,可将PHP错误重定向到日志文件:error_log = / path / to / error.log
我们可以使用php_flag表示法在httpd.conf或者.htaccess文件(如果可以访问其中一个文件)中进行设置:
php_flag error_log /web/mysite/logs/error.log
有成堆的php脚本可以做到这一点,只需在Google上搜索示例即可。如果我们想自己动手制作,那没有比读取任何其他文件更复杂的了。只需确保我们知道日志文件的位置(在httpd.conf文件中定义)和日志文件所在的格式即可。该格式也在httpd.conf中定义
对于正在寻找示例脚本的其他人,我将它们融为一体,它具有以下基础知识:
<?php exec('tail /usr/local/apache/logs/error_log', $output); ?> <Table border="1"> <tr> <th>Date</th> <th>Type</th> <th>Client</th> <th>Message</th> </tr> <? foreach($output as $line) { // sample line: [Wed Oct 01 15:07:23 2008] [error] [client 76.246.51.127] PHP 99. Debugger->handleError() /home/gsmcms/public_html/central/cake/libs/debugger.php:0 preg_match('~^\[(.*?)\]~', $line, $date); if(empty($date[1])) { continue; } preg_match('~\] \[([a-z]*?)\] \[~', $line, $type); preg_match('~\] \[client ([0-9\.]*)\]~', $line, $client); preg_match('~\] (.*)$~', $line, $message); ?> <tr> <td><?=$date[1]?></td> <td><?=$type[1]?></td> <td><?=$client[1]?></td> <td><?=$message[1]?></td> </tr> <? } ?> </table>
我们是否尝试过biterScripting?我是系统管理员,一直在解析日志。这是univx样式的脚本。 biterScripting.com->免费下载。
这是一个很小的类,可以轻松地从大文件的后面读取许多字符,而无需重载内存。通过测试设置,我们可以看到它在蚕食自己。
BigFile.php <?php $run_test = true; $test_file = 'BigFile.php'; class BigFile { private $file_handle; /** * * Load the file from a filepath * @param string $path_to_file * @throws Exception if path cannot be read from */ public function __construct( $path_to_log ) { if( is_readable($path_to_log) ) { $this->file_handle = fopen( $path_to_log, 'r'); } else { throw new Exception("The file path to the file is not valid"); } } /** * * 'Finish your breakfast' - Jay Z's homme Strict */ public function __destruct() { fclose($this->file_handle); } /** * * Returns a number of characters from the end of a file w/o loading the entire file into memory * @param integer $number_of_characters_to_get * @return string $characters */ public function getFromEnd( $number_of_characters_to_get ) { $offset = -1*$number_of_characters_to_get; $text = ""; fseek( $this->file_handle, $offset , SEEK_END); while(!feof($this->file_handle)) { $text .= fgets($this->file_handle); } return $text; } } if( $run_test ) { $number_of_characters_to_get = 100000; $bf = new BigFile($test_file); $text = $bf->getFromEnd( $number_of_characters_to_get ); echo "$test_file has the following $number_of_characters_to_get characters at the end: <br/> <pre>$text</pre>"; } ?>