gpt4 book ai didi

java - 在 java 中解析 log4j 模式

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:25 25 4
gpt4 key购买 nike

我有以下由日志文件生成的转换模式。

%d [%t] %-7p %10c{1} - %m%n

我想要的是在我的程序中采用这种模式并根据它解析日志行,可能使用正则表达式或任何东西。

最佳答案

这是 that message format 的正则表达式解析器:

public static void main(String[] args) {

// %d [%t] %-7p %10c{1} - %m%n

// ISO8601_date
// space
// [
// thread_id
// ]
// space
// priority
// space
// category (basename)
// space
// -
// space
// message
// line.separator

String[] samples = {
"1999-11-27 15:49:37,459 [thread-x] ERROR mypackage - Catastrophic system failure"
};

String regex = "(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2},\\d{3}) \\[(.*)\\] ([^ ]*) ([^ ]*) - (.*)$";

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(samples[0]);

if (m.matches() && m.groupCount() == 6) {
String date = m.group(1);
String time = m.group(2);
String threadId = m.group(3);
String priority = m.group(4);
String category = m.group(5);
String message = m.group(6);

System.out.println("date: " + date);
System.out.println("time: " + time);
System.out.println("threadId: " + threadId);
System.out.println("priority: " + priority);
System.out.println("category: " + category);
System.out.println("message: " + message);
}
}

输出是:

date: 1999-11-27
time: 15:49:37,459
threadId: thread-x
priority: ERROR
category: mypackage
message: Catastrophic system failure

关于java - 在 java 中解析 log4j 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8414579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com