java 正则表达式 log,使用正则表达式解析log4j日志文件

I have created a java application for parsing the log4j log file using regular expression, The application is working fine for the log which i have shown below

1999-11-27 15:49:37,459 [thread-x] ERROR mypackage - Catastrophic system failure

but not working for

2015-01-22 01:52:54,237 [http-bio-80-exec-5] FATAL TestLog4jServlet - Show FATAL message

My log4j ConversionPattern is given below

log4j.appender.Appender2.layout.ConversionPattern=%d [%t] %-7p %10c{1} - %m%n

Can anyone please tell me some solution for this

My code is as given below

public static void main(String[] args) {

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

Pattern p = Pattern.compile(regex);

String[] samples = {

"2015-01-22 01:52:54,237 [http-bio-80-exec-5] FATAL TestLog4jServlet - Show FATAL message"

};

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

System.out.println(m.matches());

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);

}

}

解决方案

Because there are two spaces between FATAL and TestLog4jServlet but you included only one space in your regex. So i suggest you to replace the corresponding space with + which allows one or more spaces.

(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2},\d{3}) \[(.*?)\] ([^ ]*) +([^ ]*) - (.*)$

^

|

Java regex would be,

"(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2},\\d{3}) \\[(.*)\\] ([^ ]*) +([^ ]*) - (.*)$"

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值