From 99625d4dbbe644cbeeab1d20dceddbdcad3ac3da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=94=B7?= Date: Tue, 13 May 2025 21:08:05 +0800 Subject: [PATCH] add logging for prow --- conf/moicen/prow.conf | 1 + scripts/log_to_webhook.lua | 66 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 scripts/log_to_webhook.lua diff --git a/conf/moicen/prow.conf b/conf/moicen/prow.conf index a96411b..f795c57 100644 --- a/conf/moicen/prow.conf +++ b/conf/moicen/prow.conf @@ -3,6 +3,7 @@ server { listen 443 ssl; listen 80; client_max_body_size 10M; + access_by_lua_file /usr/local/openresty/nginx/scripts/log_to_webhook.lua; # disable in local test env ssl_certificate /etc/letsencrypt/live/moicen.com/fullchain.pem; # managed by Certbot diff --git a/scripts/log_to_webhook.lua b/scripts/log_to_webhook.lua new file mode 100644 index 0000000..85c60d5 --- /dev/null +++ b/scripts/log_to_webhook.lua @@ -0,0 +1,66 @@ +-- cd /tmp +-- wget https://luarocks.org/releases/luarocks-3.11.1.tar.gz +-- tar zxpf luarocks-3.11.1.tar.gz +-- cd luarocks-3.11.1 +-- ./configure --with-lua=/usr/local/openresty/luajit +-- make +-- make install +-- +-- /usr/local/bin/luarocks install lua-resty-http +-- +-- /usr/local/bin/luarocks list + +package.path = package.path .. ';/usr/local/openresty/nginx/scripts/?.lua'; + +local cjson = require "cjson" + +-- Collect request details +local request_data = { + method = ngx.var.request_method, + uri = ngx.var.request_uri, + headers = ngx.req.get_headers(), + body = nil, + remote_addr = ngx.var.remote_addr, + timestamp = ngx.now(), + protocol = ngx.var.server_protocol, + query_string = ngx.var.query_string or "", + request_length = ngx.var.request_length +} + +-- Capture request body (if any) +ngx.req.read_body() +local body = ngx.req.get_body_data() +if body then + request_data.body = body +elseif ngx.req.get_body_file() then + local file = ngx.req.get_body_file() + local f, err = io.open(file, "r") + if f then + request_data.body = f:read("*all") + f:close() + else + ngx.log(ngx.ERR, "Failed to read body file: ", err) + request_data.body_error = err + end +end + +-- Remove sensitive headers +request_data.headers.Authorization = nil +request_data.headers.HtySudoerToken = nil + +-- Encode as JSON +local json_payload, encode_err = cjson.encode(request_data) +if not json_payload then + ngx.log(ngx.ERR, "Failed to encode JSON: ", encode_err) + return +end + +-- Write to log file +local log_file_path = "/tmp/prow_requests.log" +local file, err = io.open(log_file_path, "a") +if file then + file:write(json_payload .. "\n") + file:close() +else + ngx.log(ngx.ERR, "Failed to write to log file: ", err) +end \ No newline at end of file