nginx日志中$request_body 十六进制字符(\x22\x9B\x5C\x09\x08...)完美解决方案

在使用nginx记录访问日志时,发现在含有request_bodyPUT,POST 请求时,日志中会含有 \x22 \x9B \x5C \x09 \x08 字符,不利于阅读和处理。

具体 支持request_body的http method参见 http1.1定义 9 Method DefinitionsPayloads of HTTP Request Methods

nginx.conf 默认access_log 配置

    log_format  main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '$http_host $upstream_status $upstream_addr $request_time $upstream_response_time';复制代码

改成

    log_format json_log escape=json '{"realip":"$remote_addr","@timestamp":"$time_iso8601","host":"$http_host","request":"$request","req_body":"$request_body","status":"$status","size":$body_bytes_sent,"ua":"$http_user_agent","cookie":"$http_cookie","req_time":"$request_time","uri":"$uri","referer":"$http_referer","xff":"$http_x_forwarded_for","ups_status":"$upstream_status","ups_addr":"$upstream_addr","ups_time":"$upstream_response_time"}';复制代码

参考 How to generate a JSON log from nginx?

官方文档ngx_http_log_module.html#log_format 注意,escape是从1.11.8后新增的参数。

如果是老版本的,linux可以考虑使用shell命令替换,logstash可以考虑使用ruby处理 ,参考 Optionally support handling of \x escape codes

博客 anjia.ml/2017/06/21/…
简书 www.jianshu.com/p/8409f28f3…
掘金 juejin.im/post/5949e0…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
nginx,$request和$request_method是两个不同的变量,分别表示客户端的HTTP请求和HTTP请求方法。 其,$request包含了客户端发起的完整HTTP请求,包括请求方法、请求URI以及HTTP协议版本等信息。而$request_method则表示客户端发起的HTTP请求方法,如GET、POST等。 如果在nginx配置,$request和$request_method的值不一致,通常是由于在配置文件对这两个变量的使用不当导致的。比如,如果在一个location使用了$request_method,而在另一个location使用了$request,那么这两个变量的值就可能不一致。 举个例子,假设有如下的nginx配置: ``` location /api/ { if ($request_method = GET) { proxy_pass http://backend_server; } } location /api/post/ { proxy_pass http://backend_server; proxy_set_header Content-Type "application/x-www-form-urlencoded"; proxy_set_body $request; proxy_method POST; } ``` 上述配置,第一个location使用了$request_method变量来判断请求方法是否为GET,如果是,则转发请求给backend_server。而第二个location则使用了$request变量来设置请求体,并将请求方法设置为POST。 如果客户端发送了一个POST请求到/api/,那么第一个location会被跳过,而第二个location会将请求体设置为客户端的完整HTTP请求,导致请求方法变为POST,从而与客户端实际发起的请求方法不一致。因此,建议在nginx配置使用$request和$request_method时,要确保它们的使用方式和客户端实际发起的请求是一致的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值