Nginx JSON日志是对接ELK最轻量稳定的方式,通过escape=json构造合法JSON格式,配合Filebeat直采和ES索引模板,可避免grok解析、提升性能并保障字段类型准确。

直接让 Nginx 日志以 JSON 格式输出,是对接 ELK(Elasticsearch + Logstash + Kibana)最轻量、最稳定的方式之一。无需 Logstash 做复杂 grok 解析,省去字段提取失败风险,也避免日志解析性能瓶颈。
一、定义兼容 JSON 的 log_format
Nginx 本身不原生支持 JSON 序列化,但可通过 引号转义 + 字段拼接 构造合法 JSON 字符串。关键点:所有字符串值必须双引号包裹,特殊字符(如换行、双引号)需转义,空格和制表符要规避。
推荐基础 JSON 格式示例(含常用字段):
log_format json_log escape=json '{"@timestamp":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"upstream_addr":"$upstream_addr"}';
说明:
- escape=json 是 Nginx 1.11.8+ 引入的关键参数,自动对变量中的双引号、反斜杠、控制字符做 JSON 转义,极大降低格式损坏风险;
- 数值型字段(如
$status、$request_time)不加引号,保持 JSON 数字类型,便于 Elasticsearch 聚合分析; -
$upstream_response_time可能为空或多个值(如负载均衡),建议用"$upstream_response_time"保留字符串形式,后续在 Logstash 或 Ingest Pipeline 中再拆分; - 避免使用
$args或$query_string等可能含非法字符的变量,如需记录参数,应先清洗或改用结构化方式(如 OpenResty 注入)。
二、在 server 或 location 中启用该格式
只需在对应作用域中指定 access_log 使用新 format:
server {
listen 80;
server_name example.com;
<pre class="brush:php;toolbar:false;">access_log /var/log/nginx/access-json.log json_log;
error_log /var/log/nginx/error.log warn;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
注意:
- 确保日志目录(如
/var/log/nginx/)存在且 Nginx 进程有写权限; - 若同时保留传统日志,可并行配置多条
access_log指令; - 修改后执行
nginx -t && nginx -s reload生效,无需重启。
三、Logstash 或 Filebeat 接收时无需 grok(推荐 Filebeat)
JSON 格式日志天然适配 Filebeat 的 json.keys_under_root 配置,可零解析直采:
filebeat.inputs:
- type: filestream
paths:
- /var/log/nginx/access-json.log
json.keys_under_root: true
json.overwrite_keys: true
json.add_error_key: true
<p>output.elasticsearch:
hosts: ["<a href="https://www.php.cn/link/20b7a02ba34a9e26c207f81c4422cf7e">https://www.php.cn/link/20b7a02ba34a9e26c207f81c4422cf7e</a>"]
index: "nginx-access-%{+yyyy.MM.dd}"</p>优势:
- 跳过 Logstash 的 CPU 密集型 grok 解析,吞吐更高,延迟更低;
- Filebeat 轻量,资源占用小,适合边缘节点部署;
-
json.add_error_key: true可捕获解析失败事件,便于监控日志格式异常。
四、Elasticsearch 索引模板建议(防止字段动态映射错类型)
提前创建索引模板,明确关键字段类型,避免 request_time 被误识别为 text:
PUT _index_template/nginx-json-template
{
"index_patterns": ["nginx-access-*"],
"template": {
"mappings": {
"properties": {
"@timestamp": { "type": "date" },
"status": { "type": "integer" },
"body_bytes_sent": { "type": "long" },
"request_time": { "type": "float" },
"upstream_response_time": { "type": "text" },
"remote_addr": { "type": "ip" },
"http_user_agent": { "type": "text", "fields": { "keyword": { "type": "keyword" } } }
}
}
}
}
说明:
- 将
remote_addr设为ip类型,支持 IP 范围查询与地理分析; - 对
http_user_agent启用keyword子字段,方便精确聚合(如统计 Chrome 占比); - 模板在首个匹配索引创建时自动生效,无需手动维护 daily 索引设置。
不复杂但容易忽略:Nginx JSON 日志不是“插件”,而是靠严谨的字符串构造 + 官方 escape 支持实现的工程实践。只要 format 定义规范、采集端配置匹配、ES 映射预设合理,就能稳定支撑每秒数万级日志接入。











