Nginx - 日志格式及输出

时间:2023-03-09 06:34:52
Nginx - 日志格式及输出

1. 前言

  在 Nginx 服务器中,如果想对日志输出进行控制还是很容易的。Nginx 服务器提供了一个 HttpLogModule 模块,可以通过它来设置日志的输出格式。

2. HttpLogModule 模块

2.1 示例

Nginx - 日志格式及输出

2.2 指令

指令名称:access_log

语法:access_log [format [buffer=size] ] | off

默认值:access_log logs/access.log combined;

使用环境:http, server, location, if in location, limit_except

指令名称:log_format

语法:log_format name [escape=default|json|none] string ...;

默认值:log_format combined "...";

使用环境:http

Nginx 日志格式中,有很多参数,总结如下:

参数                        说明                                            示例
$remote_addr 客户端地址 14.116.133.170
$remote_user 客户端用户名称 --
$time_local 访问时间和时区 /Mar/::: +
$request 请求的URI和HTTP协议 "GET /city/static/js/illegals/vehicle-search.js HTTP/1.1"
$http_host 请求地址,即浏览器中你输入的地址(IP或域名) www.super.com 192.168.118.15
$status HTTP请求状态
$upstream_status upstream状态
$body_bytes_sent 发送给客户端文件内容大小
$http_referer url跳转来源 https://www.baidu.com/
$http_user_agent 用户终端浏览器等信息 Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/ Firefox/65.0
$ssl_protocol SSL协议版本 TLSv1
$ssl_cipher 交换数据中的算法 RC4-SHA
$upstream_addr 后台upstream的地址,即真正提供服务的主机地址 192.168.118.16:
$request_time 整个请求的总时间 0.205
$upstream_response_time 请求过程中,upstream响应时间 0.002

Nginx日志格式参数

指令名称:open_log_file_cache

语法:open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]; | open_log_file_cache off;

默认值:open_log_file_cache off;

使用环境:http、server、location

max - 该选项用来设置在缓存中可以存储的最大文件描述符数量。它通过最近最少使用(LRU)算法来移除缓存条目
inactive - 该选项用来设置一个时间间隔。在这个时间间隔之后,没有被命中的文件描述符将会被移除,默认值是10秒
min_uses - 该选项用来设置访问次数。在一定时间间隔内,一个文件描述符至少被访问多少次后就可以将该文件描述符放在缓存中,默认为 ,即访问一次便缓存
valid - 该选项用于设置检查同名文件存在的时间,默认为60秒
off - 关闭缓存 示例:
open_log_file_cache max= inactive=20s min_uses= valid=1m;

2.3 测试

首先,查看下 nginx 默认的日志格式:

Nginx - 日志格式及输出

测试访问,查看日志:

Nginx - 日志格式及输出

注意:这里有两个 '- -'    第一个 '-' 是 log_format 中定义的,第二个 '-' 是 $remote_user 变量为null时,返回的占位符。

Nginx - 日志格式及输出

这些变量通过上面表对比就能明白。
默认的日志格式可能不满足我们日常问题的排查,可以自行定义,这里通过是否需要转发后端服务器来分为 2类进行定义日志格式:

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$request_time"'; log_format remote_main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$request_time" "$upstream_response_time" "$upstream_addr" "$upstream_status"';

为了能够尽快的通过日志查询到异常情况,这里建议取消 http 段的全局定义日志,改为每个location 中定义一个日志文件。这样除了异常,可以快速定位。

Nginx - 日志格式及输出

access_log xxx buffer = 32k flush =5s;

这里非常有必要说一下,如果这样设置了,日志是不会实时刷新的,buffer 满 32k 才写盘;假如 buffer 不满 5s 钟后强制写盘。

最后,别忘记加上日志缓存,有利于减少服务器资源消耗。

Nginx - 日志格式及输出

2.4 测试

通过访问:
curl http://10.0.10.158/  返回的日志查看

Nginx - 日志格式及输出

最后一位是 $request_time 整个请求的总时间,我们这里只是很短的字符串测试,所以很快就处理完成。记录为 0.000

curl http://10.0.10.158/apache/index.html

Nginx - 日志格式及输出

通过这样一条日志,能够很清晰的看出来:

用户请求访问的uri:GET /apache/index.html

整个请求总耗时:0.002

后端处理耗时:0.002

后端处理请求主机socket:"10.0.10.159:8080"

后端处理返回状态:200