插件窝 干货文章 nginx中如何用JSON格式记录日志

nginx中如何用JSON格式记录日志

JSON Nginx request log 753    来源:    2025-04-27

在Nginx中使用JSON格式记录日志

要在Nginx中配置JSON格式的日志记录,你可以使用以下几种方法:

方法一:使用Nginx的log_format指令

  1. 在nginx.conf中定义一个JSON格式的日志模板:
http {
    log_format json_log escape=json '{"time": "$time_iso8601", '
                                  '"remote_addr": "$remote_addr", '
                                  '"remote_user": "$remote_user", '
                                  '"request": "$request", '
                                  '"status": "$status", '
                                  '"body_bytes_sent": "$body_bytes_sent", '
                                  '"request_time": "$request_time", '
                                  '"http_referrer": "$http_referer", '
                                  '"http_user_agent": "$http_user_agent"}';

    access_log /var/log/nginx/access.json.log json_log;
}
  1. escape=json参数会自动转义JSON中的特殊字符

方法二:使用Nginx的map指令构建更复杂的JSON

http {
    map $status $loggable {
        ~^[23]  1;
        default 0;
    }

    log_format json_log escape=json '{'
        '"timestamp": "$time_iso8601", '
        '"client_ip": "$remote_addr", '
        '"request": "$request", '
        '"status": "$status", '
        '"bytes_sent": "$body_bytes_sent", '
        '"referrer": "$http_referer", '
        '"user_agent": "$http_user_agent", '
        '"request_time": "$request_time", '
        '"upstream_response_time": "$upstream_response_time", '
        '"server_name": "$server_name", '
        '"loggable": "$loggable"'
    '}';

    access_log /var/log/nginx/access.json.log json_log if=$loggable;
}

方法三:使用Lua脚本(需要安装ngx_http_lua_module)

http {
    lua_package_path "/path/to/lua/scripts/?.lua;;";

    log_by_lua_block {
        local cjson = require "cjson"
        local log_table = {
            time = ngx.var.time_iso8601,
            remote_addr = ngx.var.remote_addr,
            request = ngx.var.request,
            status = ngx.var.status,
            body_bytes_sent = ngx.var.body_bytes_sent,
            http_referer = ngx.var.http_referer,
            http_user_agent = ngx.var.http_user_agent,
            request_time = ngx.var.request_time,
            server_name = ngx.var.server_name
        }

        local file = io.open("/var/log/nginx/access.json.log", "a")
        if file then
            file:write(cjson.encode(log_table) .. "\n")
            file:close()
        end
    }
}

注意事项

  1. 确保日志文件有正确的写入权限
  2. JSON日志文件可能会比普通日志文件大,考虑日志轮转
  3. 可以使用jq等工具方便地分析JSON日志
  4. 对于生产环境,考虑使用日志收集工具如Fluentd、Logstash等处理JSON日志

日志轮转配置示例

/etc/logrotate.d/nginx中添加:

/var/log/nginx/access.json.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

这样配置后,Nginx就会以JSON格式记录访问日志,便于后续的日志分析和处理。