Logstash傳輸給ES的數據會自動映射爲5索引,5備份,字段都爲text的的索引。這樣基本上沒法進行數據分析。
因此必須將Logstash的數據按照既定的格式存儲在ES中,這時候就要使用到ES模板技術了。在ES中能夠定義自定義模板和動態模板,以後es會自動將相關索引映射爲模板規定的格式
html
編譯動態映射模板文件bigdata.template:nginx
在Json日誌文件中的KEY的位置不固定、或字段數不明確時使用動態映射模板json
{ "template": "bigdata-template", "settings": { "index.number_of_shards": 5, "number_of_replicas": 1 }, "mappings": { "_default_": { "_all": { "enabled": true, "omit_norms": true }, "dynamic_templates": [{ "message_field": { "match": "message", "match_mapping_type": "string", "mapping": { "type": "string", "index": "analyzed", "omit_norms": true, "fielddata": { "format": "disabled" } } } }, { "string_fields": { "match": "*", "match_mapping_type": "string", "mapping": { "type": "string", "index": "not_analyzed", "doc_values": true } } }], "properties": { "@timestamp": { "type": "date" }, "@version": { "type": "string", "index": "not_analyzed" } } } } }
dynamic_templates 就是配置具體的動態模板匹配項
"match_mapping_type": "string" 是匹配固定的類型
"match": "time" 匹配字段名爲time的數據
"unmatch": "data" 不匹配字段名爲data的數據
mapping 就是將匹配的數據項映射爲定義的數據類型
app
Logstash配置文件 nginx.conf:elasticsearch
input { file { path => "/usr/local/openresty/nginx/logs/user2.log" type => "nginx-bigdata" codec => "json" } } filter { json { source => "u_data" } } output { if [type] == "nginx-bigdata" { elasticsearch { hosts => ["172.17.213.60:9200", "172.17.213.61:9200"] index => "nginx-bigdata" manage_template => false template_overwrite => true template_name => "bigdata-template" template => "/usr/local/logstash-6.2.4/bigdata.template" document_type => "nginx-bigdata" } } }
Nginx的配置文件中關於日誌格式的配置:(此處我只保留了須要的一個字段範圍)ui
escape=json :nginx 1.11.8版本後才提供此參數spa
log_format userlog escape=json '{"u_data":"$u_data"}';
...
access_log logs/user.log userlog;
產生的日誌格式:rest
{"u_data":"{\"appid\":\"nchaopai\",\"args\":{\"contentId\":0,\"duration\":111811,\"parentId\":0,\"totaltime\":0,\"type\":0},\"bk\":\"-\",\"cp_ver\":\"3.0.5\",\"duid\":\"2cba98f8ddc18464\",\"e\":\"nchaopai.main.stay-duration\",\"os\":\"A\",\"ts\":1572584611,\"ver\":\"8.11.11\"}"}
以後在Kibana裏看到就是這樣的:日誌
參考資料:https://doc.yonyoucloud.com/doc/logstash-best-practice-cn/filter/json.htmlcode