ELK基础篇5:ELK收集nginx日志

1、nginx日志转换为json格式

nginx的日志默认并不是json格式,这里我们需要把nginx的日志修改为json格式。就必须修改nginx的nginx.conf配置文件。

[root@wzy nginx]# vim  conf/nginx.conf
log_format access_json '{"@timestamp":"$time_iso8601",'
        '"host":"$server_addr",'
        '"client":"$remote_addr",'
        '"size":$body_bytes_sent,'
        '"responsetime":$request_time,'
        '"upstreamtime":"$upstream_response_time",'
        '"upstreamhost":"$upstream_addr",'
        '"http_host":"$host",'
        '"url":"$uri",'
        '"domain":"$host",'
        '"xff":"$http_x_forwarded_for",'
        '"referer":"$http_referer",'
        '"status":"$status"}';
    access_log  /var/log/nginx/access.log  access_json;
#修改完之后,我们需要重启nginx服务

格式化nginx日志为json格式是通过nginx的内置变量来实现的。

2、filebeat配置文件

[root@wzy-WEB filebeat]# cat filebeat.yml
filebeat:
  prospectors:
  - input_type: log
    tail_files: true
    backoff:  "1s"
    paths:
        - /data/nginx/logs/access_json.log
    fields:
      type: zhongguo
  - input_type: log
    tail_files: true
    backoff:  "1s"
    paths:
        - /data/nginx/logs/wzy.access_json.log
    fields:
      type: wzy
output:
  logstash:
    hosts: ["10.9.7.1:5044"]

修改完配置文件之后,一定要重启filebeat

3、编写logstash配置文件

[root@wzy_woyun config]# cat logstash.conf 
input {
  beats {
    host => '10.9.7.1'
    port => 5044
  }
}
filter {
    #定义时间戳的格式
    date {
        match => [ "timestamp" , "dd/MMM/YYYY:HH:mm:ss Z" ]
     }

   json {
       source => "message"    
       remove_field => ["message", "beat"]   
     }
  
 if [fields][type] == "wzy"  { 
       geoip {
            source => "client" 
            target => "geoip"
            database => "/usr/local/logstash-6.5.1/GeoLite2-City.mmdb" 
            add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
            add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
        }
      
      mutate {
         convert => [ "[geoip][coordinates]", "float"]
        }
  }

}
output {

 
  
 if[fields][type]=="zhongguo"{
     elasticsearch{
        hosts => ["http://127.0.0.1:9200"]
        index => "logstash-jingan-2.156-anyang-%{+YYYY.MM.dd}"
        }
  }

 else if[fields][type]=="wzy"{
       elasticsearch {
          hosts => ["http://127.0.0.1:9200"]
         index => "logstash-jingan-2.156-wanzhuang-%{+YYYY.MM.dd}"
      }
   }

}

【注意logstash中的GeoIp配置说明】

(1)geoip: IP查询插件;
(2)source: 需要通过geoip插件处理的field,一般为ip,这里因为通过控制台手动输入的是ip所以直接填message,生成环境中如果查询nginx访问用户,需先将客户端ip过滤出来,然后这里填clientip即可;
(3)target: 解析后的Geoip地址数据,应该存放在哪一个字段中,默认是geoip这个字段;
(4)database: 指定下载的数据库文件;
(5)add_field: 这里两行是添加经纬度,地图中地区显示是根据经纬度来识别。.

配置完之后,我们需要重启logstash。

猜你喜欢

转载自blog.csdn.net/u013089490/article/details/85339485