nginx日志中添加请求的response日志
換個新公司,做一些新鮮的事情,經過一天的琢磨,終于成功添加response日志
?
在nginx的日志中添加接口response的日志
由于此功能在nginx內置的功能中沒有,需要安裝第三方模塊ngx_lua,由于此模塊需要Lua語言,所以需要安裝相應的Lua語言包
1. 下載安裝LuaJIT
# cd /usr/local/src
# wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
# tar -xzvf LuaJIT-2.0.2.tar.gz
# cd LuaJIT-2.0.2
# make
?
出現如下內容表示編譯成功
OK??????? Successfully built LuaJIT
make[1]: Leaving directory `/usr/local/src/LuaJIT-2.0.2/src'
==== Successfully built LuaJIT 2.0.2 ====
# make install
出現如下內容,表示安裝成功
==== Successfully installed LuaJIT 2.0.2 to /usr/local ====
2. 下載準備nginx lua模塊
# cd /usr/local/src
# wget https://github.com/chaoslawful/lua-nginx-module/archive/v0.8.6.tar.gz
# tar -xzvf v0.8.6
3. 安裝nginx
# cd /usr/local/src/
# wget http://nginx.org/download/nginx-1.4.2.tar.gz
# tar -xzvf nginx-1.4.2.tar.gz
# cd nginx-1.4.2
//先導入環境變量,告訴nginx去哪里找luajit
# export LUAJIT_LIB=/usr/local/lib
# export LUAJIT_INC=/usr/local/include/luajit-2.0
# ./configure --prefix=/usr/local/nginx-1.4.2 --add-module=../lua-nginx-module-0.8.6
# make -j2
# make install
4.測試安裝是否成功
# cd /usr/local/nginx-1.4.2/conf/
# vi nginx.conf
lua指令方式
在server?中添加一個localtion
location /hello {default_type 'text/plain';content_by_lua 'ngx.say("hello, lua")';}然后啟動nginx
# cd?/usr/local/nginx-1.4.2/sbin
# ./nginx
?
瀏覽器訪問:
http://127.0.0.1/hello
顯示:hello, lua
?
注意點:
1.注意每個模塊的安裝目錄不能出現差錯
2.如果之前通過apt-get方式安裝了nginx,需要先刪除nginx,因為此方式下載的軟件無法編譯
3.
到此說明第三方安裝成功,
?
5.下面開始添加日志
http {log_format mylog 'response_body:$resp_body';server {#記錄nginx請求返回值 lua_need_request_body on;set $resp_body "";body_filter_by_lua ' local resp_body = string.sub(ngx.arg[1], 1, 1000)ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_bodyif ngx.arg[2] thenngx.var.resp_body = ngx.ctx.bufferedend'; location / {proxy_pass http://127.0.0.1:5000;access_log /var/log/nginx/access.log mylog;}} }
到此便成功添加response日志。
如果懂Lua語言的,可以對如下代碼進行修改,來更加符合自己的要求。
body_filter_by_lua ' local resp_body = string.sub(ngx.arg[1], 1, 1000)ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_bodyif ngx.arg[2] thenngx.var.resp_body = ngx.ctx.bufferedend';?
日志輸出時,會發現語言響應結果涉及到字符漢字的時候轉為16進制導致無法識別。
部分響應日志如下:
response_body: {\x22code\x22: 404, \x22message\x22: \x22\xE8\xAF\xB7\xE6\xB1\x82\xE7\x9A\x84\xE8\xB5\x84\xE6\xBA\x90\xE4\xB8\x8D\xE5\xAD\x98\xE5\x9C\xA8\x22, \x22data\x22: {}}?
可通過復制到python腳本進行解決。
str1=''' {\x22code\x22: 404, \x22message\x22: \x22\xE8\xAF\xB7\xE6\xB1\x82\xE7\x9A\x84\xE8\xB5\x84\xE6\xBA\x90\xE4\xB8\x8D\xE5\xAD\x98\xE5\x9C\xA8\x22, \x22data\x22: {}} ''' print(str1.encode('raw_unicode_escape').decode('utf-8'))輸入結果為:
{"code": 404, "message": "請求的資源不存在", "data": {}}?
參考網址:
https://www.cnblogs.com/aoeiuv/p/6856056.html
http://www.ttlsa.com/nginx/nginx-modules-ngx_lua/
https://blog.csdn.net/rona_lin/article/details/45028277
轉載于:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_663days.html
總結
以上是生活随笔為你收集整理的nginx日志中添加请求的response日志的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ1284:Primitive Ro
- 下一篇: SQL存储过程GET,POST 接口方法