openresty nginx 的增強版,同時基於靈活的生命周期階段,我們可以做好多靈活的事情,以下就是一個
簡單的處理請求以及響應log記錄的,原本的打算是基於log_filter_by_lua 階段處理的,后邊發現直接使用
access_log 更簡單省事,同時集成graylog靈活的log 處理能力,我們可以快速的實現proxy 請求以及響應
內容記錄
環境准備
- nginx 配置
注意處理body 部分,我們需要使用ctx 進行數據存儲方便讀取response 數據(因為nginx 基於chunk 的數據傳輸)
同時我們需要使用escape=json (格式以及中文處理)
worker_processes 1;
user root;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
gzip on;
log_format graylog2_json escape=json '{ "timestamp": "$time_iso8601", '
'"remote_addr": "$remote_addr", '
'"body_bytes_sent": $body_bytes_sent, '
'"request_time": $request_time, '
'"response_status": $status, '
'"request": "$request", '
'"request_method": "$request_method", '
'"host": "$host",'
'"request_body":"$request_body",'
'"response_body":"$resp_body",'
'"upstream_cache_status": "$upstream_cache_status",'
'"upstream_addr": "$upstream_addr",'
'"http_x_forwarded_for": "$http_x_forwarded_for",'
'"http_referrer": "$http_referer", '
'"http_user_agent": "$http_user_agent" }';
real_ip_header X-Forwarded-For;
real_ip_recursive on;
upstream api {
server xxxx:port weight=20;
server xxx:port weight=10;
server xxxx:port weight=10;
}
server {
listen 80;
charset utf-8;
default_type text/html;
location / {
set $resp_body "";
access_log /usr/local/openresty/nginx/logs/access_test.log graylog2_json;
access_log syslog:server=graylog-server:12301 graylog2_json;
body_filter_by_lua_block {
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = string.sub((ngx.ctx.buffered or "") .. resp_body, 1, 1000)
-- arg[2] is true if this is the last chunk
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
}
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
client_body_buffer_size 10M;
client_max_body_size 10G;
proxy_buffers 1024 4k;
proxy_read_timeout 120s;
proxy_connect_timeout 2s;
proxy_pass http://api;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
- graylog content pack
graylog 已經提供了相關的content pack 我們只需要導入即可,同時會創建相關的input,stream,rules,dashboard
可以參考https://github.com/petestorey26/graylog-content-pack-nginx-json
一些說明
我們最好是對於不同的log提供不同的索引(可以基於規則處理數據存儲),這樣可以減少一些問題,同時對於openresty
的body_filter 需要做一些處理才能准確的獲取response數據
參考資料
https://github.com/petestorey26/graylog-content-pack-nginx-json
https://nginx.org/en/docs/syslog.html
https://docs.graylog.org/en/3.3/
https://docs.graylog.org/en/3.3/pages/content_packs.html