从log4j日志中提取数据的正则表达式模式是什么



我有一个日志文件,其中包含以下条目:

[08/30/19 16:00:01:001 EDT] [SRNotes_Worker-1] INFO com.emc.clm.srnotes.schedule.SRNotesItemProcessor Started processing the SrTriageFile instance with ID 38 and file ID 250339290
[08/30/19 16:00:01:001 EDT] [SRNotes_Worker-1] TRACE org.springframework.jdbc.core.StatementCreatorUtils Setting SQL statement parameter value: column index 2, parameter value [73651266], value class [java.lang.String], SQL type unknown

我可以使用什么正则表达式模式来提取以下中的所有相关字段

Timestamp: [08/30/19 16:00:01:001 EDT]
Thread: [SRNotes_Worker-1]
Level: INFO
Class: com.emc.clm.srnotes.schedule.SRNotesItemProcessor
Message: Started processing the SrTriageFile instance with ID 38 and file ID 250339290

我写了一个函数,它遍历字符串的每个字符,并检查"["、空格和其他类似的规则。基于此,我拆分了日志条目。但我知道这不是一个优雅的解决方案。我应该使用regex,但我对此没有足够的了解。

您应该尝试了解regex的工作原理,以便构建自己的表达式,但这里有一个示例:

([[^]]+])s([[^]]+])s([^s]+)s([^n]+)
//Finds a sequence starting with an [ and ending with the next ]
//(between anything is allowerd; n > 0 times any symbol that is not a ])
//The brackets ( ) are symboling a group, which shuold be selected
([[^]]+])
//Symbols one space
s
//Same as the first
([[^]]+])
//space again
s
//selects anyhting untill the next sapce
([^s]+)
//space one last time
/s
//selects anyhting to the linebreak
([^n]+) 

你可能想为你的情况进一步调整这个,但这应该是让你开始。

如果您的行看起来总是如图所示,您也可以在这里使用String.split方法。在每个空格处拆分线条,但如果空格位于方括号内,则不要拆分。将拆分长度限制为5:

String line = "[08/30/19 16:00:01:001 EDT] [SRNotes_Worker-1] INFO com.emc.clm.srnotes.schedule.SRNotesItemProcessor Started processing the SrTriageFile instance with ID 38 and file ID 250339290";
//line.split("\s")  split a string at each space
//line.split("\s",5) split a string at each space limit length of result to 5
//line.split("\s(?![^\[]*[\]])") split a string at each space but not inside []

以上所有的结合在一起,你可以做一些类似的事情:

Arrays.stream(line.split("\s(?![^\[]*[\]])",5)).forEach(System.out::println);

或者将它们保存到阵列中

String[] myData = line.split("\s(?![^\[]*[\]])",5);

并且访问每个元素,myData[0]是你的TimestampmyData[1]是你的Thread。。。

最新更新