Nginx 日志默认为普通文本的格式,例如,下面是 Nginx 的一行访问日志:
118.194.170.243 - - [02/May/2018:15:36:20 +0800] "GET /180.html?preview_id=180&preview_nonce=d3424efefd&_thumbnail_id=-1&preview=true HTTP/1.1" 200 11283 "https://www.ywcsb.vip/wp-admin/post.php?post=180&action=edit" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:59.0) Gecko/ 0100101 Firefox/59.0" "-" "."
为了以后方查看,可以将 Nginx 的日志改成 json 的格式。修改后的 json 日志格式如下所示:
{ "@timestamp": "2022-02-21 17:24:24", "remote_addr": "184.105.247.196", "http_x_forwarded_for": "-", "host": "140.143.5.71", "request_uri":"https://140.143.5.71/","remote_user": "-", "request": "GET / HTTP/1.1", "status": 301, "body_bytes_sent": 178, "http_referer": "-", "http_user_agent": "-", "request_time": "0.000" }
为了修改 Nginx 的日志格式改成 json,需要修改 Nginx 的配置文件:
1、首先在没有server下自定义时间变量
server{
# 自定义时间变量
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
set $hour $4;
set $minutes $5;
set $seconds $6;
}
listen 80 default ;
listen [::]:80 default;
}
2、Nginx 的配置文件为 /etc/nginx/nginx.conf。 http_x_forwarded_for
获取后端真实IP地址
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$pipe"';
log_format log_json '{ "timestamp": "$year-$month-$day $hour:$minutes:$seconds", '
'"remote_addr": "$remote_addr", '
'"http_x_forwarded_for": "$http_x_forwarded_for", '
'"host": "$host", '
'"request_uri":"$scheme://$http_host$request_uri",'
'"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" '
'}';
access_log /var/log/nginx/access.json log_json;
}
修改 Nginx 的配置,重启 Nginx ,便可以看到 json 格式的日志,重启 Nginx:
nginx -s reload
发表评论
共 0 条评论
暂无评论