在 nginx 配置文件 http { } 模块中,使用 log_format 来设置 nginx 请求日志纪录格式
实例:
# 添加$request_body参数
# main 是定义的格式名称
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$http_do_dev" "$http_do_channel" "$http_do_v" '
'"$request_body" $request_time $upstream_response_time';
# json 格式,用于日志监听处理,可filebeat 监听日志记录到redis
log_format json escape=json '{"@client":"$remote_addr","time":"$time_local","domain":"$host","method":"$request_method","request_url":"$request_uri",'
'"status":"$status","scheme":"$scheme","http_version":"$server_protocol",'
'"size":"$body_bytes_sent","request_body":"$request_body","ua": "$http_user_agent","referer": "$http_referer",'
'"http_x_forwarded_for":"$http_x_forwarded_for","request_time":"$request_time","upstream_response_time":"$upstream_response_time"}';
escape=json 是从1.11.8后新增的参数。
如果是老版本的,linux可以考虑使用shell命令替换,logstash可以考虑使用ruby处理 ,参考 Optionally support handling of \x escape codes
对于想在nginx日志中记录某个header变量,可在logformat中添加带 http 前缀的自定义header字段变量,即可将指定的自定义header字段打印到log中。
如 想打印 Authorization,在log_format 中添加变量 $http_Authorization ;
像user-agent这种带横线的字段,需要写成user_agent,nginx会自动做处理的。
如 想打印 user-agent ,在log_format 中添加变量 $http_user_agent
./vhost/*.conf
# 在每一个server的日志配置中添加自己定义的格式名称
access_log /alidata/log/nginx/*.access.log main;
$remote_addr #记录访问网站的客户端ip地址
$remote_port # 客户端的port
$remote_user # 如果nginx有配置认证,该变量代表客户端认证的用户名
$time_local #记录访问时间与时区
$request #用户的http请求起始行信息,包括方法名、请求地址、http版本
$status #http状态码,记录请求返回的状态码,例如:200、301、404等
$body_bytes_sent #服务器发送给客户端的响应body字节数
$http_referer #记录此次请求是从哪个连接访问过来的,可以根据该参数进行防盗链设置。
$http_user_agent #记录客户端访问信息,例如:浏览器、手机客户端等
$http_x_forwarded_for #当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置
$request_body # post上传的数据
$request_time # 整个请求的总时间
$upstream_response_time # 请求过程中,和php-fpm的交互时间
$args # 请求中的参数,如www.123.com/1.php?a=1&b=2的$args就是a=1&b=2
$content_length # HTTP请求信息里的”Content-Length”
$conten_type # HTTP请求信息里的”Content-Type”
$document_root # nginx虚拟主机配置文件中的root参数对应的值
$document_uri 或 $uri # 当前请求中不包含指令的URI,如www.123.com/1.php?a=1&b=2的$document_uri就是1.php,不包含后面的参数
$request_uri # 请求的链接,包括和args
$host # 主机头,也就是域名
$http_cookie # 客户端的cookie信息
$request_body_file # 做反向代理时发给后端服务器的本地资源的名称
$request_method # 请求资源的方式,GET/PUT/DELETE等
$request_filename # 当前请求的资源文件的路径名称,相当于是document_uri的组合
$scheme # 请求的协议,如ftp,http,https
$server_protocol # 客户端请求资源使用的协议的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等
$server_addr # 服务器IP地址
$server_name # 服务器的主机名
$server_port # 服务器的端口号
[1]
Optionally support handling of \x escape codes: https://github.com/logstash-plugins/logstash-codec-json/issues/2