Logstash 配置文件的基本结构包含三个主要部分:input、filter 和 output。每个部分都可以包含多个插件配置。
配置文件结构
confinput { # 输入插件配置 } filter { # 过滤器插件配置 } output { # 输出插件配置 }
1. Input 配置
Input 部分定义数据源,常用配置示例:
文件输入
confinput { file { path => "/var/log/*.log" start_position => "beginning" sincedb_path => "/dev/null" type => "syslog" } }
Beats 输入
confinput { beats { port => 5044 } }
Kafka 输入
confinput { kafka { bootstrap_servers => "localhost:9092" topics => ["logs"] group_id => "logstash-consumer" } }
2. Filter 配置
Filter 部分对数据进行处理和转换,常用过滤器:
Grok 过滤器
conffilter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } }
Date 过滤器
conffilter { date { match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"] } }
Mutate 过滤器
conffilter { mutate { rename => { "old_field" => "new_field" } remove_field => ["temp_field"] convert => { "status" => "integer" } } }
GeoIP 过滤器
conffilter { geoip { source => "client_ip" target => "geoip" } }
3. Output 配置
Output 部分定义数据输出目标:
Elasticsearch 输出
confoutput { elasticsearch { hosts => ["http://localhost:9200"] index => "logstash-%{+YYYY.MM.dd}" document_type => "_doc" } }
文件输出
confoutput { file { path => "/path/to/output.log" } }
标准输出
confoutput { stdout { codec => rubydebug } }
条件判断
Logstash 支持条件语句来控制数据流:
conffilter { if [type] == "apache" { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } } else if [type] == "nginx" { grok { match => { "message" => "%{NGINXACCESS}" } } } } output { if [status] >= 400 { elasticsearch { hosts => ["http://localhost:9200"] index => "error-logs-%{+YYYY.MM.dd}" } } else { elasticsearch { hosts => ["http://localhost:9200"] index => "access-logs-%{+YYYY.MM.dd}" } } }
配置文件验证
使用以下命令验证配置文件语法:
bashbin/logstash --config.test_and_exit -f /path/to/config.conf
最佳实践
- 模块化配置:将不同功能的配置拆分到多个文件
- 使用条件判断:根据数据类型应用不同的处理逻辑
- 合理使用过滤器:避免不必要的过滤器以提高性能
- 日志级别设置:在生产环境中使用适当的日志级别
- 配置文件管理:使用版本控制系统管理配置文件