修改nginx日志格式為json


Nginx 日志默認為普通文本的格式

100.116.122.100 - - [25/Oct/2018:13:53:45 +0800] "GET /css/bootstrap.css HTTP/1.1" 404 532 "https://boss.zbt.com/finance/partner/create-account-gateway?id=529460523813568512" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36" "220.191.185.22"

為了便於利用 Elastic Stack 日志平台收集展示 Nginx 的日志,可以將 Nginx 的日志改成 json 的格式。

{"@timestamp": "29/Nov/2018:14:37:45 +0800","user_ip":"-","lan_ip":"100.116.111.202","log_time":"2018-11-29T14:37:45+08:00","user_req":"HEAD / HTTP/1.0","http_code":"200","body_bytes_sents":"0","req_time":"0.121","user_ua":"-"}

修改 nginx.conf 文件, /etc/nginx/nginx.conf

修改http模塊為如下

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" '
                                          '$http_host '
                      ' $upstream_response_time  $request_time  $upstream_addr $geoip_country_code';
    log_format  log_json '{"@timestamp": "$time_local","user_ip":"$http_x_real_ip","lan_ip":"$remote_addr","log_time":"$time_iso8601","user_req":"$request","http_code":"$status","body_bytes_sents":"$body_bytes_sent","req_time":"$request_time","user_ua":"$http_user_agent"}';   
     access_log  /var/log/nginx/access.log  log_json;

有些server單獨設置了log的,需要在log后面添加 log_json格式

測試

nginx  -t

重啟

nginx  -s reload

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM