Created
November 11, 2020 10:33
-
-
Save mashayev/d45e301c6f84805654176f95b78808ff to your computer and use it in GitHub Desktop.
Request / Response login in NGINX with lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local list_req_headers = {} | |
for k, v in pairs(ngx.req.get_headers()) do | |
list_req_headers[#list_req_headers+1] = tostring(k) .. ": " .. tostring(v) | |
end | |
local list_res_headers = {} | |
for k, v in pairs(ngx.resp.get_headers()) do | |
list_res_headers[#list_res_headers+1] = tostring(k) .. ": " .. tostring(v) | |
end | |
local cjson = require "cjson" | |
local errlog = require "ngx.errlog" | |
exchange = { | |
type = "exchange", | |
request = { | |
timestamp = ngx.var.time_iso8601, | |
originalClientIp = ngx.var.remote_addr, | |
method = ngx.var.request_method, | |
uri = ngx.var.request_uri, | |
httpVersion = "HTTP/1.1", | |
headers = list_req_headers, | |
body = ngx.encode_base64(ngx.var.request_body), | |
}, | |
response = { | |
timestamp = ngx.var.time_iso8601, | |
httpVersion = "HTTP/1.1", | |
statusCode = ngx.var.status, | |
headers = list_res_headers, | |
body = ngx.encode_base64(ngx.arg[1]), | |
} | |
} | |
local exchange_text = cjson.encode(exchange) | |
errlog.raw_log(ngx.INFO, exchange_text) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In nginx configuration file, in server block: | |
server { | |
error_log /var/log/nginx/error.log info; | |
lua_need_request_body on; | |
body_filter_by_lua_file /etc/nginx/lua/json_log.lua; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Output - Exchange Log Line Example | |
{ | |
"type": "exchange", | |
"request": { | |
"timestamp": "2019-06-01T01:00:00.000Z", | |
"originalClientIp": "13.12.11.10", | |
"method": "POST", | |
"uri": "/foo/bar", | |
"httpVersion": "HTTP/1.1", | |
"headers": ["Content-Type: text/json", "Connection: close", "Host: | |
hfoo.com", "Content-Length: 16"], | |
"body": "{\"key\": \"value\"}" | |
}, | |
"response": { | |
"timestamp": "2019-06-01T01:00:00.000Z", | |
"httpVersion": "HTTP/1.1", | |
"statusCode": "200 OK", | |
"headers": ["Content-Type: text/json", "Connection: close", | |
"Content-Length: 16"], | |
"body": "e1wia2V5XCI6IFwidmFsdWVcIn0=" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment