💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # Managing Mutiline Events(管理多行事件) 某些用例产生跨多行文本的事件。为了正确处理这些事件,Logstash需要知道哪些行是单个事件的一部分。 处理多行事件是复杂的并且依赖于适当的事件排序。确保有序的日志处理的最佳方法是在管道中尽可能早的处理。 [Multiline](https://www.elastic.co/guide/en/logstash/6.5/plugins-codecs-multiline.html) 编码器是Logstash管道中处理多行事件的首选工具。Multiline编解码器使用一组简单的规则将单个输入中的行合并。 > <font color=#DC143C size=4>IMPORTANT</font>:如果你使用的是支持多个主机的Logstash input插件,如beats,你应该使用诸如[Multiline](https://www.elastic.co/guide/en/logstash/6.5/plugins-codecs-multiline.html) 编解码器来处理多行事件。Doing so may result in the mixing of streams and corrupted event data.(这样做可能会导致流混合和损坏的事件数据。)这种情况,你需要在事件数据被发送到Logstash之前处理多行事件。 配置多行编解码器最重要的是下面这些: + `Pattern`选项指定一个正则表达式。被匹配的行被解析为前一行的连续或者新的多行时间的开始。你可以在此配置选项中使用grok正则表达式模板。 + `What`选项的值有两个:`previous`或`next`。`Previous`表示在`pattern`选项中匹配到的值是前一行的一部分。`Next`表示在`pattern`选项中匹配到的值是接下来的行的一部分。`Negate`选项将没有被`pattern`选项中匹配到的行应用到多行编解码器。(The `negate` option applies the multiline codec to lines that *do not* match the regular expression specified in the `pattern` option.) 关于[multiline](https://www.elastic.co/guide/en/logstash/6.5/plugins-codecs-multiline.html)编解码器插件的更多信息和配置选项,参考完整文档。 # Multiline编解码器配置示例 本章节的示例包括以下用例: + 将Java堆栈跟踪组合为单个事件 + 将C风格的行持续组合到单个事件中(Combining C-style line continuations into a single event) + 将来自时间戳的多行事件进行组合 ## Java堆栈跟踪 Java 堆栈跟踪由多行组成,在初始行开始后的每一行都以空白开始,如: ```log Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) ``` 要在Logstash中将这些行整合为一个事件,使用下面的multiline编解码器配置: ```conf input { stdin { codec => multiline { pattern => "^\s" what => "previous" } } } ``` 这个配置将任何以空白开始的行合并到前一行。 ## Line Continuations(行延续?) 一些编程语言使用`\`字符在行的结尾表示行没有结束,如: ```c printf ("%10.10ld \t %10.10ld \t %s\ %f", w, x, y, z ); ``` 要在Logstash中将这些行整合为一个事件,使用下面的multiline编解码器配置: ```conf input { stdin { codec => multiline { pattern => "\\$" what => "next" } } } ``` 这个配置将任何以`\`字符结束的行合并到接下来的行。 ## 时间戳 来自诸如Elasticsearch等服务的活动日志通常以时间戳开头,其次是具体的信息,如: ```log [2015-08-24 11:49:14,389][INFO ][env ] [Letha] using [1] data paths, mounts [[/ (/dev/disk1)]], net usable_space [34.5gb], net total_space [118.9gb], types [hfs] ``` 要在Logstash中将这些行整合为一个事件,使用下面的multiline编解码器配置: ```conf input { file { path => "/var/log/someapp.log" codec => multiline { pattern => "^%{TIMESTAMP_ISO8601} " negate => true what => previous } } } ``` 这个配置使用`negate`选项来指定任何没有以时间戳开头的行属于前一行。