Skip to content

Instantly share code, notes, and snippets.

@indyone
Last active September 30, 2020 07:54
Show Gist options
  • Save indyone/559fad9364d93a430154eef179b0676d to your computer and use it in GitHub Desktop.
Save indyone/559fad9364d93a430154eef179b0676d to your computer and use it in GitHub Desktop.
Log full request including the all headers & body with Nginx/OpenResty

Usage

  1. Ensure that you have a working Docker installation
  2. Create the folder conf.d on your working path
  3. Download and copy the default.conf from this gist into the conf.d folder
  4. Run the docker command
docker run -p 80:80 -v <working-path>/conf.d:/etc/nginx/conf.d --name nginx-logging openresty/openresty:alpine

Make sure you replace the <working-path> with the full path of the directory that contains the conf.d folder.

All requests will be responded with a 200 OK status code and some ummy JSON and will be logged including the request headers and body.

The logs can be viewed by accessing the URL: http://localhost/_logs

log_format custom escape=none '[$time_local] $remote_addr\n$request\n$request_headers\n$request_body\n';
map $request_body $loggable {
'' 0;
'-' 0;
default 1;
}
server {
listen 80;
server_name localhost;
access_log /usr/local/openresty/nginx/logs/access_custom.log custom if=$loggable;
location / {
set_by_lua $request_headers '
local h = ngx.req.get_headers()
local request_headers_all = ""
for k, v in pairs(h) do
request_headers_all = request_headers_all .. ""..k..": "..v..string.char(10)
end
return request_headers_all
';
add_header Content-Type application/json;
echo_read_request_body;
echo '{ "result": "OK", "code" : 100 }';
}
location /_logs {
add_header Content-Type text/plain;
access_log off;
root /usr/local/openresty/nginx/logs;
try_files /access_custom.log =404;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment