【问题标题】:parse the log4j pattern in java在java中解析log4j模式
【发布时间】:2012-01-14 22:06:01
【问题描述】:

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

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

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

【问题讨论】:

  • 你能给我们举个例子吗?

标签: java regex parsing log4j


【解决方案1】:

这是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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多