前面我們介紹了使用logstash監控nginx日誌,nginx日誌默認是httpd格式的日誌,對於開發人員來說,json格式更加友好,因此本篇我們就介紹如何修改nginx的默認日誌格式,以及如何使用logstash的插件解析json格式的日誌,然後寫入到ES中。
ELK系列(一)、安裝ElasticSearch+Logstash+Kibana+Filebeat-v7.7.0
ELK系列(二)、在Kibana中使用RESTful操作ES庫
ELK系列(四)、Logstash讀取nginx日誌寫入ES中
ELK系列(五)、Logstash修改@timestamp時間爲日誌的產生時間
------------------------修改nginx日誌爲json格式並使用logstash讀取到es內-----------------
nginx配置
vim /usr/local/nginx/conf/nginx.conf
添加如下內容
log_format log_json '{"remote_addr": "$remote_addr", '
'"ident": "-", '
'"user": "$remote_user", '
'"timestamp": "$time_local", '
'"request": "$request", '
'"status": $status, '
'"bytes": $body_bytes_sent, '
'"referer": "$http_referer", '
'"agent": "$http_user_agent", '
'"x_forwarded": "$http_x_forwarded_for"'
' }';
access_log logs/access-json.log log_json;
重啓nginx
sbin/nginx -s reload
可以看到在nginx日誌目錄新多了一個access-json.log文件。
logstash配置
vim /opt/app/logstash-7.7.0/config/logstash_nginxlog2es_json.conf
input {
# 從文件讀取日誌信息
file {
path => "/usr/local/nginx/logs/access-json.log" #修改爲json日誌文件
type => "nginx_access_json"
start_position => "beginning"
}
}
filter {
json {
source => "message"
remove_field => ["beat","offset","tags","prospector"] #移除字段,不需要採集
}
date {
match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"] #匹配timestamp字段
target => "@timestamp" #將匹配到的數據寫到@timestamp字段中
}
}
output {
# 輸出es
elasticsearch {
hosts => ["wykd:9200"]
index => "nginx-%{+YYYY.MM.dd}"
}
}
重啓logstash
bin/logstash -f config/logstash_nginxlog2es_json.conf
驗證ES內的數據
希望本文對你有幫助,請點個贊鼓勵一下作者吧~ 謝謝!