【发布时间】:2010-09-14 15:15:12
【问题描述】:
我想创建一个脚本来解析或理解 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 文件中定义)和 format your log files 所在的位置。格式也在 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>";
}
?>
【讨论】: