大家好,我试图从文件中对日志消息进行排序。 我的日志文件如下所示 http://kopy.io/tA8bv 我希望得到像这样的东西
['debug'] => [
['logs'] => [
['log message'] => [
'2016-04-10',
'2016-04-10',
'2016-04-10'
],
['log message'] => [
'2016-04-10',
'2016-04-10',
'2016-04-10'
],
...
]
],
['Crit'] => [
['logs'] => [
['log message'] => [
'2016-04-10',
'2016-04-10',
'2016-04-10'
],
['log message'] => [
'2016-04-10',
'2016-04-10',
'2016-04-10'
],
...
]
]
这是我的代码,但它无法正常工作,省略了一些行
$file = fopen(self::DIRECTORY.$filename, 'rb');
while(($line = fgets($file)) !== false) {
if($this->lineHasDate($line)) {
$logDate = $this->getLogDate($line);
$logType = $this->getTypeOfLog($line);
$content .= $line;
// $content ='';
}
while(!$this->lineHasDate($line) && ($line = fgets($file)) !== false) {
// echo $line;
$content .= $line;
}
$this->logs[$logType]['logs'][] = $content;
$content = '';
}
fclose($file);
答案 0 :(得分:0)
指定的代码 - 循环遍历文件循环文件, - 有点过于复杂,更容易出错。
尝试这样,在你的例子中它适用于我。它的读取和调试更简单,更简单:
$file = fopen (self::DIRECTORY.$filename, 'rb');
while (($line = fgets($file)) !== false)
{
if ($this->lineHasDate($line))
{
$logDate = $this->getLogDate($line);
$logType = $this->getTypeOfLog($line);
$this->logs[$logType]['logs'][] = $line;
$currentLog = &$this->logs[$logType]['logs'][count($this->logs[$logType]['logs']) - 1];
}
else
{
if (!isset($currentLog)) // In case of trash lines before logs begin
continue;
else
$currentLog .= $line;
}
}
fclose($file);
另外,当您将省略的行提供给它时,请测试$this->lineHasDate($line)
返回true
。