2 ELK收集nginx的json格式日志

    技术2022-07-11  126

    为了便于利用 ELK日志平台收集展示 Nginx 的日志,可以将 Nginx 的日志改成 json 的格式 https://www.jianshu.com/p/b6ba259777e7

    1.修改nginx配置文件

    [root@db01 ~]# vim /etc/nginx/nginx.conf ##打开nginx配置文件添加这些信息 log_format json '{ "time_local": "$time_local", ' '"remote_addr": "$remote_addr", ' '"referer": "$http_referer", ' '"request": "$request", ' '"status": $status, ' '"bytes": $body_bytes_sent, ' '"agent": "$http_user_agent", ' '"x_forwarded": "$http_x_forwarded_for", ' '"up_addr": "$upstream_addr",' '"up_host": "$upstream_http_host",' '"up_resp_time": "$upstream_response_time",' '"request_time": "$request_time"' ' }'; ##再将日志引用改成json access_log /var/log/nginx/access.log json;

    2.清空nginx原先日志

    [root@db01 ~]# > /var/log/nginx/access.log

    3.重启nginx,使其配置文件生效

    [root@db01 ~]# systemctl restart nginx

    4.使用ab命令做模拟访问 也可以使用浏览器访问,手动生成访问日志

    [root@db01 ~]# ab -n 100 -c 100 http://172.16.210.53/

    5.查看日志 这时候,就能看见日志格式变成了json格式

    [root@db01 ~]# tailf /var/log/nginx/access.log { "time_local": "22/Jun/2020:08:53:21 +0800", "remote_addr": "172.16.210.53", "referer": "-", "request": "GET / HTTP/1.0", "status": 200, "bytes": 4833, "agent": "ApacheBench/2.3", "x_forwarded": "-", "up_addr": "-","up_host": "-","up_resp_time": "-","request_time": "0.000" }

    6.使用es-head查看是否建立索引 filebeat会收集数据,然后导出至elasticsearch 7.修改filebeat配置文件

    [root@db01 ~]# vim /etc/filebeat/filebeat.yml filebeat.inputs: - type: log enabled: true paths: - /var/log/nginx/access.log ##添加这两行信息,使其能解析json格式的日志 json.keys_under_root: true json.overwrite_keys: true output.elasticsearch: hosts: ["172.16.210.53:9200"]

    8.重启filebeat

    [root@db01 ~]# systemctl restart filebeat

    9.回到kibana的web界面创建索引 点击management 点击Create index pattern

    输入filebeat导出到elaticsearch的索引名字,再点击Next stup 过滤选项名选择@timestamp再点击Create index pattern 再点击Discover就能查看到创建的索引的数据了 再点击小三角就能看到全部都是一一对应的json格式数据了 然后可以通过选择对应的字段名,来查看指定想要知道的信息 比如想查看访问的ip都有谁,见选择remote_addr再点击add 只过滤显示访问的ip 再想查看这些ip访问的状态码,就添加status 以此类推,想要显示什么就添加什么

    如果不想查看某个ip的访问信息,也可以排除某个ip

    Processed: 0.009, SQL: 9