乐闻世界logo
搜索文章和话题

Logstash 配置文件的基本结构是什么,如何编写一个完整的配置?

2月21日 15:17

Logstash 配置文件的基本结构包含三个主要部分:input、filter 和 output。每个部分都可以包含多个插件配置。

配置文件结构

conf
input { # 输入插件配置 } filter { # 过滤器插件配置 } output { # 输出插件配置 }

1. Input 配置

Input 部分定义数据源,常用配置示例:

文件输入

conf
input { file { path => "/var/log/*.log" start_position => "beginning" sincedb_path => "/dev/null" type => "syslog" } }

Beats 输入

conf
input { beats { port => 5044 } }

Kafka 输入

conf
input { kafka { bootstrap_servers => "localhost:9092" topics => ["logs"] group_id => "logstash-consumer" } }

2. Filter 配置

Filter 部分对数据进行处理和转换,常用过滤器:

Grok 过滤器

conf
filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } }

Date 过滤器

conf
filter { date { match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"] } }

Mutate 过滤器

conf
filter { mutate { rename => { "old_field" => "new_field" } remove_field => ["temp_field"] convert => { "status" => "integer" } } }

GeoIP 过滤器

conf
filter { geoip { source => "client_ip" target => "geoip" } }

3. Output 配置

Output 部分定义数据输出目标:

Elasticsearch 输出

conf
output { elasticsearch { hosts => ["http://localhost:9200"] index => "logstash-%{+YYYY.MM.dd}" document_type => "_doc" } }

文件输出

conf
output { file { path => "/path/to/output.log" } }

标准输出

conf
output { stdout { codec => rubydebug } }

条件判断

Logstash 支持条件语句来控制数据流:

conf
filter { 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}" } } }

配置文件验证

使用以下命令验证配置文件语法:

bash
bin/logstash --config.test_and_exit -f /path/to/config.conf

最佳实践

  1. 模块化配置:将不同功能的配置拆分到多个文件
  2. 使用条件判断:根据数据类型应用不同的处理逻辑
  3. 合理使用过滤器:避免不必要的过滤器以提高性能
  4. 日志级别设置:在生产环境中使用适当的日志级别
  5. 配置文件管理:使用版本控制系统管理配置文件
标签:Logstash