首先將數據傳給logstash,它將數據進行過濾和格式化(轉成JSON格式),然後傳給Elasticsearch進行存儲、建搜索的索引,kibana提供前端的頁面再進行搜索和圖表可視化,它是調用Elasticsearch的接口返回的數據進行可視化。
在logstash 配置文件中寫清我們的日誌文件的路徑:
input {
file {
path => "xxxx.log" #監聽文件路徑
}
}
文件只要變動 就會更新到es中,
我們可以在kibana看到 我們日誌中的字段都已json的形式 轉載在_source
@timestamp 則是裝入的時間戳
node調用 Elasticsearch
var elasticsearch = require('elasticsearch');
var esClient = new elasticsearch.Client({
host: 'http://192.168.129.119:9200',
log: 'error'
});
module.exports = esClient;
當前只使用到了search方法,
更多方法:https://www.npmjs.com/package/elasticsearch
根據需求,按用戶、機構、API等查看各個API的訪問情況,聚合數據,按小時統計
如 按機構 ,
var index_date="logstash-"+options.date.replace(/-/g, ".");
esClient.search({
index: index_date,
body: {
"size": 0,
"query": {
"bool": {
"must": [
org_search,
user_search,
api_search,
status_search_su
] ,
"must_not": [
status_search_err
],
"should": []
}
},
"aggs": {
"date": {
"date_histogram": {
"field": "@timestamp",
"interval": "hour",
"format": "yyyy-MM-dd HH",
"min_doc_count" : 0,
"extended_bounds" : {
"min": options.date+" 00",
"max": options.date+" 23"
}
},
"aggs": {
"group_by_org": {
"terms": {
"field": "request.headers.orgid.keyword",
"size": 1000
}
}
}
}
}
}
}, function (error, response) {
if(error!=null){
callback(error,null);
}else{
var data=response.aggregations.date.buckets;
callback(null,data);
}
});
其中:
org_search 是 org_search={"term":{"request.headers.orgid.keyword":""+options.orgid+""}}; orgid是機構ID,
"query": {
"bool": {
"must": [
] ,
"must_not": [
],
"should": []
}
}
用於多重過濾,如查詢某機構下某用戶某返回狀態碼,,,must是需符合,,must_not是除這個結果之外,,例如想查詢異常的 就把,,
status_search_err={"term":{"response.status":"200"}} 爲200返回正常的放入 must_not中
而aggs就用來聚合數據,,
按時間戳 整成這一天中 每小時,,都有哪些機構,,分別的訪問次數是多少
最後的結果類似於:
"buckets":[{
"key_as_string":"2018-01-22 00",
"key":1,
"doc_count":1
},{
"key_as_string":"2018-01-22 01",
"key":2,
"doc_count":2
},
...
]}
實現top5 功能:
如最新的5個api 的url統計
"aggs": {
"top_tags": {
"terms": {
"field": "api.name.keyword",
"size": 5
},
"aggs": {
"top_url_hits": {
"top_hits": {
"sort": [
{
"@timestamp": {
"order": "desc"
}
}
],
"_source": {
"includes": [ "api.upstream_url" ,"response.status"]
},
"size" : 1
}
}
}
}
}
按最新時間顯示前五個