nginx输出json日志

json日志优点
json本身就是结构化的。
几乎所有编程语言都可以很轻松地解析它,便于数据采集和分析。
日志格式配置
# 文本格式
# log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
# JSON格式
log_format log_json '{"@timestamp": "$time_iso8601", '
'"connection": "$connection", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"request_method": "$request_method", '
'"request_uri": "$request_uri", '
'"server_protocol": "$server_protocol", '
'"status": "$status", '
'"body_bytes_sent": "$body_bytes_sent", '
'"http_referer": "$http_referer", '
'"http_user_agent": "$http_user_agent", '
'"http_x_forwarded_for": "$http_x_forwarded_for", '
'"request_time": "$request_time"}';
修改 Nginx 的配置,重启 Nginx ,便可以看到 json 格式的日志,重启 Nginx。
sudo /usr/local/nginx/sbin/nginx -s reload此时查看最新日志,就会发现日志变为json格式,例如
{"@timestamp": "2021-09-08T22:36:21+08:00", "connection": "6605", "remote_addr": "123.139.52.164", "remote_user": "-", "request_method": "GET", "request_uri": "/", "server_protocol": "HTTP/1.1", "status": "304", "body_bytes_sent": "0", "http_referer": "-", "http_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36", "http_x_forwarded_for": "-", "request_time": "0.000"}
log_format指令中常用变量
$bytes_sent
发送给客户端的总字节数
$body_bytes_sent
发送给客户端的字节数,不包括响应头的大小
$connection
连接序列号
$connection_requests
当前通过连接发出的请求数量
$request_length
请求长度(包括请求行,请求头和请求体)
$request_time
请求处理时长,单位为秒,精度为毫秒,从读入客户端的第一个字节开始,直到把最后一个字符发送张客户端进行日志写入为止
$status
响应状态码
$time_iso8601
标准格式的本地时间,形如“2017-05-24T18:31:27+08:00”
$time_local
通用日志格式下的本地时间,如"24/May/2017:18:31:27 +0800"
$http_referer
请求的referer地址。
$http_user_agent
客户端浏览器信息。
$remote_addr
客户端IP
$http_x_forwarded_for
当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置。
$request
完整的原始请求行,如 "GET / HTTP/1.1"
$remote_user
客户端用户名称,针对启用了用户认证的请求
$request_uri
从客户端发送来的原生请求URI,包括参数。它不可以进行修改。
$uri
重写后/改变的URI。
相关推荐
-
「nginx」十、nginx的location配置详解2026-07-04 00:51:45 -

最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代
最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代2026-07-04 00:21:47 -
PHP读取Excel内的图片2026-07-03 00:07:41 -
mysql:Otter跨机房数据同步(单向)2026-07-03 00:02:48 -

在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境
在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境2026-07-02 00:15:08