我已经使用php从日志文件中解析了日志,并将这些行推送到了数组中。
[2020-01-21 18:01:23] local.INFO: Backup success
[2020-01-21 18:11:03] local.DEBUG: aid=1 bac=2343
[2020-01-21 18:21:29] production.CRITICAL:send failed
[2020-01-21 18:51:01] production.WARNING:limit 7/9 reached
如何从每一行中更有效地获得期望的输出?
$final = [];
foreach($lines as $line){
//best way to parse data to $date, $env, $type, $message from $line variable?
$arr = [
'date'=> $date,
'env'=> $env,
'type'=> $type,
'message'=> $message
];
array_push($final, $arr);
}
期望
[
{
"date":"2020-01-21 18:01:23",
"env":"local",
"type":"INFO",
"message":"Backup success"
},
{
"date":"2020-01-21 18:21:29",
"env":"production",
"type":"CRITICAL",
"message":"send failed"
},
...
...
]
答案 0 :(得分:2)
尝试此版本。
$re = '/^\[(?<date>.*)\]\s(?<env>\w+)\.(?<type>\w+):(?<message>.*)/m';
$str = '[2020-01-21 18:01:23] local.INFO: Backup success
[2020-01-21 18:11:03] local.DEBUG: aid=1 bac=2343
[2020-01-21 18:21:29] production.CRITICAL:send failed
[2020-01-21 18:51:01] production.WARNING:limit 7/9 reached';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
// Print json string
echo json_encode($matches, JSON_PRETTY_PRINT);
答案 1 :(得分:0)
希望这可以解决您对问题的回答:)
$lines = '[2020-01-21 18:01:23] local.INFO: Backup success';
$arr = explode('] ', $lines);
$arr1 = explode(': ', $arr[1]);
$arr2 = explode('.', $arr1[0]);
$arr[0] = str_replace("[","",$arr[0]);
echo 'date = ' . $arr[0];
echo '<br>';
echo 'env = ' .$arr2[0];
echo '<br>';
echo 'type = ' .$arr2[1];
echo '<br>';
echo 'message = ' .$arr1[1];
echo '<br>';
答案 2 :(得分:0)
爆炸,子字符串,修剪和数组解构的混合:
$final = [];
foreach ($lines as $line) {
[$envType, $message] = explode(':', substr($line, 22));
[$env, $type] = explode('.', $envType);
$final[] = [
'date' => substr($line, 1, 19),
'env' => $env,
'type' => $type,
'message' => trim($message)
];
}
$jsonFormat = json_encode($final, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);