配置日志格式为JSON

Nginx使用json的格式记录日志,方便Elasticsearch对其检索

编辑配置文件

--编辑主配置文件
[root@linux /]# vim /usr/local/nginx/conf/nginx.conf
http {
...............  #省略部分内容 
include /usr/local/nginx/conf.d/*.conf;
log_format log_json '{"@timestamp":"$time_local",'
  '"host": "$server_addr",'
  "clientip": "$remote_addr",'
  '"size": $body_bytes_sent,'
  '"responsetime": $request_time,'
  '"upstreamtime": "$upstream_response_time",'
  '"upstreamhost": "$upstream_addr",'
  '"http_host": "$host",'
  '"url": "$uri",'
  '"xff": "$http_x_forwarded_for",'
  '"referer": "$http_referer",'
  '"agent": "$http_user_agent",'
  '"status": "$status"}';
...............  #省略部分内容 
}

参数解释

$server_add  服务器地址
$remote_add  记录客户端IP地址
$body_bytes_sent 传送页面的字节数
$request_time    Nginx开始收到client 请求,到将请求发回给client 期间过去的时间
$upstream_response_time  
$upstream_addr  后台upstream的地址,真正提供服务的主机地址
$host         请求地址,浏览器输入的地址
$uri          请求中的当前URI,不包括主机名
http_x_forwarded_for     记录客户端IP地址
$http_referer            客户请求的完整URI
$http_user_agent         获取用户的相关信息,包括用户使用的浏览器,操作系统等信息
$status        获取HTTP请求状态

--编辑子配置文件
[root@linux /]# vim /usr/local/nginx/conf.d/www.conf 
server {
  listen 80;
  server_name www.endvv.com;
  access_log logs/access.log log_json;

location / {
  root /www/html;
  index index.html index.php;
 }
}

重启 Nginx

nginx -s reload

客户机访问

--使用客户端访问WEB
[root@linux /]# echo "172.16.0.19 www.endvv.com" >>/etc/hosts
[root@linux /]# curl www.endvv.com

--查看WEB 日志
[root@linux /]# cat /usr/local/nginx/logs/access_json.log
{"@timestamp":"13/Nov/2020:23:31:24 +0800","host": "172.16.0.19","clientip": "172.16.0.1","size": 6,"responsetime": 0.000,"upstreamtime": "-","upstreamhost": "-","http_host": "www.endvv.com","url": "/index.html","xff": "-","referer": "-","agent": "curl/7.64.0","status": "200"}
Last modification:February 17, 2022
If you think my article is useful to you, please feel free to appreciate