我们需要解析几个日志文件,并对找到的日志条目运行一些统计信息(例如某些消息的出现次数、事件的峰值等)。问题在于编写一个日志解析器,它将处理几种日志格式,并允许我在很少工作的情况下添加一种新的日志格式。
为了使事情变得更简单,我现在只看一些基本类似于以下内容的日志:
[11/17/11 14:07:14:030 EST] MyXmlParser E Premature end of file
因此,每个日志条目将包含一个timestamp
、originator
(日志消息)、level
和日志message
。一个重要的细节是消息可能有多个行(例如堆栈跟踪)。日志条目的另一个实例可以是:
17-11-2011 14:07:14 ERROR MyXmlParser - Premature end of file
我正在寻找一种很好的方法来指定日志格式,以及实现解析器的最适当的技术。我想到了正则表达式,但我认为处理诸如多行消息(例如堆栈跟踪)之类的情况会很棘手。
实际上,当我考虑多行消息的可能性时,为特定日志格式编写解析器的任务听起来并不容易。如何解析这些文件?
理想情况下,我可以将类似的内容指定为日志格式:
[%TIMESTAMP] %ORIGIN %LEVEL %MESSAGE
或
%TIMESTAMP %LEVEL %ORIGIN - %MESSAGE
显然,我必须为每个字段分配正确的转换器,以便正确地处理它(例如时间戳)。
有人能给我一些好的想法,说明如何以健壮和模块化的方式实现这一点(我正在使用)吗?
发布于 2013-10-11 13:47:36
最后,我没有编写自己的代码,也没有使用原木存放物。
发布于 2011-11-28 17:06:57
AWStats是一个很好的日志解析器,开源,您可以随意使用它生成的数据库。
发布于 2011-12-09 16:38:37
例如,您可以使用扫描仪和一些regexes。下面是我为解析一些复杂日志所做的工作的一个片段:
private static final Pattern LINE_PATTERN = Pattern.compile(
"(\\S+:)?(\\S+? \\S+?) \\S+? DEBUG \\S+? - DEMANDE_ID=(\\d+?) - listener (\\S+?) : (\\S+?)");
public static EventLog parse(String line) throws ParseException {
String demandId;
String listenerClass;
long startTime;
long endTime;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
Matcher matcher = LINE_PATTERN.matcher(line);
if (matcher.matches()) {
int offset = matcher.groupCount()-4; // 4 interesting groups, the first is optional
demandeId = matcher.group(2+offset);
listenerClass = matcher.group(3+offset);
long time = sdf.parse(matcher.group(1+offset)).getTime();
if ("starting".equals(matcher.group(4+offset))) {
startTime = time;
endTime = -1;
} else {
startTime = -1;
endTime = time;
}
return new EventLog(demandeId, listenerClass, startTime, endTime);
}
return null;
}
因此,对于regexes和group,它运行得很好。
https://stackoverflow.com/questions/8299440
复制相似问题