如何根据模式拆分日志?

AsT*_*TeR 2 scripting log-files logging

我希望能够根据其中找到的模式拆分日志文件。

例如处理所有日志并查找/(\w+)\s匹配/myresource但排除/myresource/anythingelse,将所有内容重定向到/var/log/extractedlog/myresource/access.log. 我可以使用一点 grep 轻松编写脚本,但是,尝试实时执行此操作可能会使问题变得更难。例如,我想两次调用该程序而不生成重复项。

编辑

这是一个完整的代码,可以使用 syslog-ng 获得类似的东西/etc/syslog-ng/syslog-ng.conf(信用获得接受的答案):

# no-parse let syslog load any source
source s_unparsed_source {
    file("/var/log/myservice/access.log"
        flags(no-parse));
};

# Just protect the input and avoid syslog-ng header to be added in the final log
template t_preserve_message {
    template("$MSG\n");
    template_escape(no);
};

# This will filter the message only matching the given expression
filter f_match_pattern1 {
    match("\/pattern1");
};

destination d_target1 {
    file("/var/log/target/pattern1/access.log" template(t_preserve_message));
};

# The actual logging instruction which wraps everything
log {
    source(s_unparsed_source);
    filter(f_math_pattern1);
    destination(d_target1);
};
Run Code Online (Sandbox Code Playgroud)

daw*_*wud 5

无论rsyslogsyslog-ng(GNU / Linux中用于管理日志的两种常用程序)有办法做到这一点。

使用syslog-ng,您可以定义与正则表达式匹配的过滤器:

filter myfilter {
  not match("regex" value("\/usr\/sbin\/run-crons"))
  and not match("regex" value("vmware-checker"));
}
Run Code Online (Sandbox Code Playgroud)

并且您还可以使用模式数据库,它允许事件和动作触发的关联。

还有logstash,它具有高级过滤功能。具体来说,它有一个grep过滤器:

filter {
  grep {
    match => { "message" => "hello world" }
  }
}
Run Code Online (Sandbox Code Playgroud)