nginx日志输出配置json格式

修改nginx配置文件

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:

扩展:log_format指令中常用的一些变量
地址:https://www.cnblogs.com/sanduzxcvbnm/p/14250758.html

posted @ 2021-01-08 13:47  哈喽哈喽111111  阅读(3032)  评论(0编辑  收藏  举报