如何使用不同类型的消息解析日志文件

How to parse log file with different types of messages

我有一个包含复杂消息类型的日志文件。这是一个例子:

2016-07-07 13:30:02 [Main] *** Program start ***
2016-07-07 13:30:02 [UnzipFile] Before file collection
2016-07-07 13:30:02 [GetZipCol] Start get sorted zip file collection
2016-07-07 13:30:02 [GetZipCol] End get sorted zip file collection
2016-07-07 13:30:02 [Main] [ERROR] No unzip file
2016-07-07 13:30:03 [Main] *** Program end ***

以下grok模式只适用于前4行,不适用于第5行。

grok{
    match => {"message" => ['%{Date:Date}%{SPACE}%{Time:Time}%{SPACE}%{WORD:Job}%{SPACE}%{GREEDYDATA:Message}']}
        }

我想知道如何修改 grok 模式以从上一条消息中捕获[ERROR]。有没有人知道如何做到这一点?

这是我在 conf

中的输出部分
if [Message] == "*** Program start ***" {
    elasticsearch { 
    hosts => ["localhost:9200"] 
    index => "log-%{+YYYY.MM.dd}"
    template => "C:/logstash/log.json"
    template_overwrite => true
    }   
}
if [Message] == "*** Program end ***" {
    elasticsearch { 
    hosts => ["localhost:9200"] 
    index => "log-%{+YYYY.MM.dd}"
    template => "C:/logstash/log.json"
    template_overwrite => true
    }   
}  
if [Level] =~ /.+/ {
    elasticsearch { 
    hosts => ["localhost:9200"] 
    index => "log-%{+YYYY.MM.dd}"
    template => "C:/logstash/log.json"
    template_overwrite => true
    }   
}

如果我只想抓取程序开始和结束时的事件以及出错的事件,其他事件可以丢弃。但是,根据我所写的。我只能掌握带有[错误]的数据。我应该如何掌握其他数据?是否有更简单的方法来代替输入 3 if 条件语句?谢谢

谢谢。

我不是 logstash 方面的专家,但快速浏览一下文档,这些 "grok" 模式似乎是对普通正则表达式的抽象。

因此,为 ERROR 级别消息添加一个可选的非捕获组可能会奏效。即 (?:\[%{WORD:Level}\]%{SPACE})?。这样整行就变成了:

grok{
    match => {"message" => ['%{Date:Date}%{SPACE}%{Time:Time}%{SPACE}%{WORD:Job}(?:\[%{WORD:Level}\]%{SPACE})?%{GREEDYDATA:Message}']}
}

作为参考,我使用了这部分文档:https://www.elastic.co/guide/en/logstash/current/config-examples.html#_processing_syslog_messages

您可以在同一个 grok 过滤器中使用两个模式,如果第一个失败,则使用第二个。因此,在您的情况下,第一个模式将尝试捕获 [ERROR],第二个模式将是您答案中的模式。
我认为它更具可读性。

grok{
  match => {
    "message" => [
       '%{DATE:Date}%{SPACE}%{TIME:Time}%{SPACE}\[%{WORD:Job}\]%{SPACE}\[%{WORD:Level}\]%{SPACE}%{GREEDYDATA:Message}',
       '%{DATE:Date}%{SPACE}%{TIME:Time}%{SPACE}\[%{WORD:Job}\]%{SPACE}%{GREEDYDATA:Message}'
   ]}
}