网上统一方法:

修改nginx.conf配置文件

http {
include       mime.types;
default_type  application/octet-stream;
charset  utf-8;

# 原有日志格式,不能注释或者去掉

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 log_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"'
' }';

access_log  logs/access.log log_json; # 引用日志格式名称

(省略内容)

}

在 Nginx 的配置文件nginx.conf中,我们定义了两种的日志格式:main和log_json,其中,main为普通的文本格式,log_json为 json 格式。log_json其实就是手工构造一个 json 字符串。定义了 json 的日志格式后,便可以指定 access log 为 json 格式,修改 Nginx 的配置,重启 Nginx ,便可以看到 json 格式的日志,重启 Nginx。


自用修改版,记录post

# json日志格式
    log_format log_json '{"@timestamp": "$time_local", '
                        '"remote_addr": "$remote_addr", '
                        '"referer": "$http_referer", '
                        '"request": "$request", '
                        '"agent": "$http_user_agent", '
                        '"x_forwarded": "$http_x_forwarded_for", '
                        '"host": "$upstream_http_host",'
                        '"request_body": "$request_body",'
                        '"up_resp_time": "$upstream_response_time",'
                        '"request_time": "$request_time"'
                        ' }';
Last modification:September 8, 2022
如果觉得我的文章对你有用,请随意赞赏