為了相對(duì)簡(jiǎn)單的實(shí)現(xiàn)用戶訪問(wèn)區(qū)域?qū)崟r(shí)分布圖榨汤,就采用了Logstash + Elasticsearch 索引Nginx access log 實(shí)現(xiàn)了此功能(這里主要講實(shí)現(xiàn)方法)蠕搜。
優(yōu)勢(shì):相對(duì)簡(jiǎn)單易實(shí)現(xiàn)。
劣勢(shì):相對(duì)明顯收壕,由于用戶來(lái)源歸屬地信息妓灌,是通過(guò)用戶外網(wǎng)IP的GEOIP庫(kù)計(jì)算出來(lái)的,可能有很一小部分用戶歸屬地不太準(zhǔn)確(比如啼器,除聯(lián)通電信以外的ISP的外網(wǎng)IP)旬渠。
定制業(yè)務(wù)效果頁(yè)面截圖效果如下:
此業(yè)務(wù)效果圖需要自行開(kāi)發(fā)俱萍,目前使用百度EchartJS做為前段圖表展示端壳,后端使用做為Jobs實(shí)時(shí)輸出歸屬地統(tǒng)計(jì)接口。
好了枪蘑,說(shuō)了這么多损谦。下面我就說(shuō)說(shuō)相關(guān)配置方法:
1.第一步先配置nginx access 輸出日志格式
#nginx.conf
log_format main '$server_name $realip $remote_addr $remote_port "$http_x_forwarded_for" $remote_user [$time_local] "$request" '
'$status $body_bytes_sent $content_length "$http_referer" '
'"$http_user_agent" $request_time $upstream_response_time $cookie_xotoken $cookie_UM "$http_cookie" $proxy_host $upstream_addr $upstream_cache_status';
2.配置logstash
安裝geoip插件
/usr/share/logstash/bin/logstash-plugin install logstash-filter-geoip
下載最新的GEOIP庫(kù)
cd /etc/logstash/ && wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz && tar xf GeoLite2-City.tar.gz&&mv GeoLite2-City*/GeoLite2-City.mmdb
logstash規(guī)則配置(各位看官請(qǐng)根據(jù)自己的日志格式做出相應(yīng)修改):
input {
file {
path => "/data/logs/nginx/nginx.access.log"
}
}
filter {
grok {
patterns_dir => "/etc/logstash/conf.d/patterns"
match => {
message => '%{HOSTNAME:hostname} %{IPV4:realip} %{IPV4:remote_ip} %{BASE10NUM:source_port} "%{DATA:xforwarded_for .*}" %{NGUSER:userauth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{URIPATHPARAM:request} HTTP/%{NUMBER:httpversion}" (?:%{NUMBER:request_status}|-) (?:%{NUMBER:body_bytes_sent}|-) (?:%{NUMBER:content_length}|-) (?:"(?:%{URI:referrer}|-)"|%{QS:referrer}) (%{QS:user_agent}) (%{NUMBER:request_time}|-) (%{NUMBER:upstream_response_time}|-) (%{DATA:wowoohruserid .*}|-) (%{DATA:um_distinctid .*}|-) "(%{DATA:cookies .*}|-)"'
}
}
date {
match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss +0800"]
target => "@timestamp"
timezone => "Asia/Shanghai"
"locale" => "en"
}
geoip {
source => "realip"
target => "geoip"
database => "/etc/logstash/GeoLite2-City.mmdb"
}
}
output {
elasticsearch {
hosts => "10.1.1.1"
index => "nginxlog-%{+YYYY.MM.dd}"
}
}
3.ES查詢以及數(shù)據(jù)整合方法
ES設(shè)置text允許索引:
{"properties": {"geoip.region_name": {"type":"text","fielddata":'true'}}}
ES聚合查詢語(yǔ)句:
{"aggs": {"group_by_name": {"terms": {"field": "geoip.region_name.keyword",'size':'50'}}},"size": 0}
在設(shè)置以上查詢之后,需自行開(kāi)發(fā)Api Jobs接口實(shí)時(shí)吐數(shù)據(jù)給前端頁(yè)面進(jìn)行展示岳颇。
前端頁(yè)面使用angularjs+echart開(kāi)發(fā)(較復(fù)雜就不在這贅述照捡,可根據(jù)自己項(xiàng)目實(shí)現(xiàn)展示),實(shí)現(xiàn)動(dòng)態(tài)前后端分離接口數(shù)據(jù)請(qǐng)求话侧。