前言
Codec 是 logstash 从 1.3.0 版开始新引入的概念(Codec 来自 Coder/decoder 两个单词的首字母缩写)。
在此之前,logstash 只支持纯文本形式输入,然后以过滤器处理它。但现在,我们可以在输入 期处理不同类型的数据,这全是因为有了 codec 设置。
所以,这里需要纠正之前的一个概念。Logstash 不只是一个input | filter | output
的数据流,而是一个 input | decode | filter | encode | output
的数据流!codec 就是用来 decode、encode 事件的。
codec 的引入,使得 logstash 可以更好更方便的与其他有自定义数据格式的运维产品共存,比如 graphite、fluent、netflow、collectd,以及使用 msgpack、json、edn 等通用数据格式的其他产品等。
事实上,我们在第一个 “hello world” 用例中就已经用过 codec 了 —— rubydebug 就是一种 codec!虽然它一般只会用在 stdout 插件中,作为配置测试或者调试的工具。
multiline示例
下面记录一个工作中实际用到的多行日志解析:
Logging Time:2018-01-05 09:29:06,303 Thread Id:[131] Logging Level:ERROR Logging Type: Plugin
Operation User:admin
Operation Type:
Plugin Type:first detail Plugin Version:1.0.0.0
Logging Description:ce5-1 process ce5-1_603096 fai
Exception Information:System.Exception: calculate error
Logging Time:2018-01-05 09:29:06,303 Thread Id:[131] Logging Level:ERROR Logging Type: Plugin
Operation User:admin
Operation Type:
Plugin Type:first detail Plugin Version:1.0.0.0
Logging Description:ce5-1 process ce5-1_603096 fai
Exception Information:System.Exception: calculate error
需要解析出来的格式为:
时间:2018-01-05 09:29:06,303
模块:Plugin+1.0.0.0
详情:Logging Description + Exception Information
日志级别:ERROR
用户名:admin
配置文件logstash-shipper-Test.conf为:
input{
file {
path => "D:/TestLog/*.log"
codec => multiline {
#charset => "GB2312"
pattern => "^Logging Time"
negate => true
what => "previous"
}
type=> "TAS"
sincedb_path => "D:/TestLog/Test_sincedb"
}
}
filter {
if [type] == "Test" {
grok {
patterns_dir => ["./patterns"]
match => { "message" => "(?m)Logging%{SPACE}Time:%{TIMEPATTERN:time}%{SPACE}Thread%{SPACE}Id:\[%{NUMBER:pid}\]%{SPACE}Logging%{SPACE}Level:%{LOGLEVEL:level}%{SPACE}Logging%{SPACE}Type:%{GREEDYDATA:ossType}?%{SPACE}Operation%{SPACE}User:%{GREEDYDATA:user}?%{SPACE}Operation%{SPACE}Type:%{USERNAME:operate_type}?%{SPACE}Plugin%{SPACE}Type:%{GREEDYDATA:operateName}%{SPACE}Plugin%{SPACE}Version:%{GREEDYDATA:logVersion}?%{SPACE}Logging%{SPACE}Description:%{GREEDYDATA:detail}?%{SPACE}Exception%{SPACE}Information:%{GREEDYDATA:excp_detail}" }
}
mutate{
add_field => {"system" => "%{type}"}
add_field => {"module" => "system"}
}
mutate {
update=>{"module"=>"%{operateName}"}
}
mutate {
merge => {"module" => "logVersion"}
merge => {"detail" => "excp_detail"}
}
mutate {
join => {"module" => "+"}
join => {"detail" => "+"}
}
mutate {
gsub => ["module","\r\n",""]
}
date{
match => ["time","yyyy-MM-dd HH:mm:ss,SSS"]
locale => "en"
#timezone => "Etc/GMT-8"
target => "@timestamp"
add_tag => ["tmatch"]
}
mutate{
remove_field => ["excp_detail"]
}
}
}
output {
redis{
host => "127.0.0.1"
port => 6379
key => "logstash-Test"
data_type => "list"
}
stdout {
codec => rubydebug
}
}