首頁  >  文章  >  後端開發  >  nginx日誌中新增請求的response日誌

nginx日誌中新增請求的response日誌

不言
不言原創
2018-05-05 09:49:542565瀏覽

這篇文章主要介紹了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_body
   if ngx.arg[2] then
    ngx.var.resp_body = ngx.ctx.buffered
   end
  ';
     
  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_body
   if ngx.arg[2] then
    ngx.var.resp_body = ngx.ctx.buffered
   end
  ';

日誌輸出時,會發現語言回應結果涉及到字元漢字的時候轉為16進位導致無法辨識。

部分回應日誌如下:

response_body:    {\x22code\x22: 404, \x22message\x22: \x22\xE8\xAF\xB7\xE6\xB1x22: \x22\xE8\xAF\xB7\xE6\xB1x822 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": {}}###################

以上是nginx日誌中新增請求的response日誌的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn