美奇科技 发表于 2018-11-10 10:53:50

ELK监控日志nginx(集成Geoip)

  实验环境:之前ELK已经初步安装完毕了,只需要将nginx的日志发送过来就可以了,nginx的IP为:192.168.137.101。因为服务端只是收集日志的所以下面的操作完全是在nginx机器上面完成的。在这里感谢《ELK stack权威指南》这本书,下面配置的内容都是借鉴的这本书。
  #/opt/logstash/bin/logstash-plugin install logstash-filter-geoip
  安装这个插件,以前的老版本需要自己下载GeoIP还有这个插件的数据库,现在都不需要了,已经集合成插件了,直接在配置文件调用就好了。
  #vim /etc/logstash/conf.d/nginx-out-es.conf
  我的logstash配置文件在这个路径,里面的配置内容都是按照上面提到的那本书配置的
input {  
    file {
  
      path => "/usr/local/nginx/logs/access.log"
  
      codec => json
  
    }
  
}
  
filter {
  
    geoip {
  
      source => "clientip"
  
      fields => ["city_name", "country_code2", "country_name", "latitude", "longitude", "region_name"]
  
      remove_field => ["", ""]
  
    }
  
    mutate {
  
      split => [ "upstreamtime", "," ]
  
    }
  
    mutate {
  
      convert => [ "upstreamtime", "float" ]
  
    }
  
}
  
output {
  
    elasticsearch {
  
      hosts => ["192.168.137.191:9200"]
  
      index => "nginx-access-log-%{+YYYY.MM.dd.HH}"
  
      workers => 1
  
      template_overwrite => true
  
    }
  
}
  #vim /usr/local/nginx/conf/nginx.conf
log_format json '{"@timestamp":"$time_iso8601",'  
               '"host":"$server_addr",'
  
               '"clientip":"$remote_addr",'
  
               '"size":$body_bytes_sent,'
  
               '"responsetime":$request_time,'
  
               '"upstreamtime":"$upstream_response_time",'
  
               '"upstreamhost":"$upstream_addr",'
  
               '"http_host":"$host",'
  
               '"url":"$uri",'
  
               '"xff":"$http_x_forwarded_for",'
  
               '"referer":"$http_referer",'
  
               '"agent":"$http_user_agent",'
  
               '"status":"$status"}';
  

  
access_loglogs/access.logjson;
  这个nginx的配置内容也是根据书上面的内容写出来的,最下面的一些城市信息是自己填上去的。
  #/opt/logstash/bin/logstash --configtest -f /etc/logstash/conf.d/nginx-out-es.conf
  测试一下logstash的配置文件语法是否正确
  #service nginx restart
  重启nginx使配置文件生效
  #nohup /opt/logstash/bin/logstash -f /etc/logstash/conf.d/nginx-out-es.conf &
  后台静默启动longstash
  下面就可以再服务端查看接收到的日志信息了

  上面图片是内网访问的结果

  上面这个图片是公网来访问的结果,会自动添加地理位置及城市信息和坐标位置
  除了使用上述的方法还可以使用nginx自己本身的geoip模块(需要下载依赖库GeoIP,GeoIP-devel,perl-Geo-IP)来分析来访的IP地址,然后将完整的信息全都输送到ES端,但是这个方法会增加nginx的一些资源消耗。方法很简单在添加完模块后下载GeoIP的数据库文件,在nginx里面指定GeoIP数据库的文件路径,记得添加权限否则无法读取,其他的配置内容不需要修改,重启nginx就可以了。具体方法nginx的官网是有的很详细。


页: [1]
查看完整版本: ELK监控日志nginx(集成Geoip)