我有program.log文件,它的名称为;
2016-12-12 this is a log line 1 [warning]
2016-12-12 this is a log line 2 [warning]
2016-12-12 this is a log line 3 [error]
2016-12-13 this is a log line 4 [error]
2016-12-14 this is a log line 5 [error]
2016-12-14 this is a log line 6 [warning]
我无法在PHP中编写读取此文件并处理其内容的代码并提供日志摘要。 最终输出已知,但我无法手动执行此操作。
最终输出看起来像
2016-12-12 warning:2 error: 1
2016-12-13 warning:0 error: 1
2016-12-14 warning:1 error: 1
答案 0 :(得分:0)
你不是要求解决方案吗?这仍然适用于使用rejex和一些数组。
<?php
/**
* Created by PhpStorm.
* User: Vaibs
* Date: 22-07-2017
* Time: 21:52
*/
$logCurrentDate = null;
$logPrevDate = null;
$report = array();
if ($file = fopen("a.log", "r")) {
$logTypeErrorCount = 0;
$logTypeWarningCount = 0;
$isLogError = false;
while (!feof($file)) {
$line = fgets($file);
$a = array();
preg_match_all("~^\d{4}\-\d{2}-\d{2}+ (this is a log line)+ (\d+)+ \[(.*)\]~", $line, $a);
$logCurrentDate = substr($a[0][0], 0, 10);
$logTypeCurrent = $a[3][0];
$isLogError = ($logTypeCurrent == "error") ? true : false;
if ($logCurrentDate != $logPrevDate) {
$report[$logCurrentDate] = array("Warning" => $logTypeWarningCount = $isLogError ? 0 : 1, "Error" => $logTypeError = $logTypeErrorCount = $isLogError ? 1 : 0);
} else {
if ($isLogError) {
$logTypeErrorCount = $logTypeErrorCount + 1;
} else {
$logTypeWarningCount = $logTypeWarningCount + 1;
}
$report[$logCurrentDate]['Warning'] = $logTypeWarningCount;
$report[$logCurrentDate]['Error'] = $logTypeErrorCount;
}
$logPrevDate = $logCurrentDate;
}
// print_r($report);
foreach ($report as $x => $x_value) {
echo $x . ' warning: ' . $x_value['Warning'] . ' error: ' . $x_value['Error'] . PHP_EOL;
}
fclose($file);
}
a.log:您的日志文件
2016-12-12 this is a log line 1 [warning]
2016-12-12 this is a log line 2 [warning]
2016-12-12 this is a log line 3 [error]
2016-12-13 this is a log line 4 [error]
2016-12-14 this is a log line 5 [error]
2016-12-14 this is a log line 6 [warning]