每一个你不满意的现在,都有一个你不努力的曾经。

Nginx 日志转JSON


描述

Nginx 以宝塔安装为例

1)修改nginx.conf配置文件


    [root@localhost conf]# vim /www/server/nginx/conf/nginx.conf

    # 在http{} 中添加

    # 原有日志格式,不能注释
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $request_time';
    # json日志格式
    log_format json '{"@timestamp": "$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"'
                        ' }';

2)修改vhosts/*.conf配置文件

    # 错误 access_log error_log 在后面同时添加 json 会报错
    access_log  /www/wwwlogs/test.com.log json;
    error_log  /www/wwwlogs/test.com.error.log json;

    # 正确
    access_log  /www/wwwlogs/test.com.log json;
    error_log  /www/wwwlogs/test.com.error.log;

3)结果

{"@timestamp": "16/Mar/2023:17:04:43 +0800", "remote_addr": "192.168.5.197", "referer": "-", "request": "GET / HTTP/1.1", "status": 200, "bytes": 43, "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0", "x_forwarded": "-", "up_addr": "unix:/tmp/php-cgi-74.sock","up_host": "-","up_resp_time": "0.001","request_time": "0.001" }
Card image cap

每一个你不满意的现在,都有一个你不努力的曾经。