那么,我试图解析PHP错误日志。因此,我建立了下面的类:如何解析PHP错误日志?
<?php
/**
* Created by PhpStorm.
* User: toton
* Date: 2/29/2016
* Time: 8:16 AM
*/
final class error_parser
{
private $log_file_path;
private $current_line;
private $recent;
/**
* error_parser constructor.
* Takes in the path of the error log file of PHP ERROR LOG FILE.
* And another param for checking to get the direction to traverse the file.
* @param string $log_file_path
* @param bool $recent
*/
public function __construct($log_file_path, $recent = true)
{
$this->log_file_path = $log_file_path;
$this->recent = $recent;
$this->_parse();
return true;
}
/**
* Parses the PHP ERROR LOG, and pushes an array with the following structure:
* array(
* "date" => {DATE},
* "severity" => {SEVERITY},
* "message" => {message},
* "stack_trace" => array(each({STACK_TRACE})) || false;
*);
* to the main array.
* !!!! IMPORTANT !!!!
* STACK TRACE IS NOT SUPPORTED AT THIS MOMENT
* TODO: IMPLEMENT STACK TRACE
* MILESTONE: NEXT_MAJOR RELEASE
*/
private function _parse() {
$contents = file_get_contents($this->log_file_path);
if(!$contents){
throw new Exception("Log file does not exist.", 2);
}
$lines = explode("\n", $contents);
if($this->recent) {
$lines = array_reverse($lines);
}
for($this->current_line = 0; $this->current_line < count($lines); $this->current_line++) {
parse_loop:
$current_line = trim($lines[$this->current_line]);
if(strlen($current_line) == 0) {
//If the line is empty throw it to the dustbin.
// SORRY, FOR THE GOTO.
// GOD PLEASE FORGIVE ME!
$this->current_line = $this->current_line + 1;
goto parse_loop;
}
if($current_line[0] != "[") {
// NOT SUPPORTING STACK TRACES AT THE MOMENT
$this->current_line = $this->current_line + 1;
goto parse_loop;
}
$dateArr = array();
preg_match('~^\[(.*?)\]~', $current_line, $dateArr);
$date = array(
"date" => explode(" ", $dateArr[1])[0],
"time" => explode(" ", $dateArr[1])[1]
);
$severity = "";
if(strpos($current_line, "PHP Warning")) {
$severity = "WARNING";
} elseif(strpos($current_line, "PHP Notice")) {
$severity = "NOTICE";
} elseif(strpos($current_line, "PHP Fatal error")) {
$severity = "FATAL";
} elseif(strpos($current_line, "PHP Parse error")) {
$severity = "SYNTAX_ERROR";
} else {
$severity = "UNIDENTIFIED_ERROR";
}
}
}
}
(嗯,有可能在代码:-P一些不好的做法有)例如
一个错误可能是这一点 - [28-Dec-2015 07:51:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_pspell.dll' - The specified module could not be found.
无论如何,我能够提取错误的日期和类型。但我找不到解析错误信息的方法。
所以我的问题是,我该如何解析PHP错误日志中的错误信息?
在此先感谢,干杯!
为什么豆你需要解析PHP的错误文件?要找到你的代码的问题?你可以随时设置你自己的错误和excepion处理程序,这是你知道的首选方式。 –
不,我正在为我的网站构建一个管理员仪表板,我只想要一个Web界面来监视我的错误日志。 – Ikari
这就是我的想法。您需要为此构建您自己的错误处理程序,您可以将这些错误以您想要的格式保存在数据库或文件中。我将发布一个简单的解决方案,你从那里去。 –