nginx日誌中$request_body 十六進位制字元(\x22\x9B\x5C\x09\x08...)完美解決方案

趙安家發表於2017-06-21

在使用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…

相關文章