由于此功能在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 LuaJITmake[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進制導致無法識別。
部分響應日志如下:
新聞熱點
疑難解答