if ngx.ctx.log_request then local cjson = require "cjson" local args = ngx.req.get_uri_args() local query_string = "" pcall(function() query_string = cjson.encode(args) end) local request_headers = ngx.req.get_headers() local token = request_headers["token"] or args["token"] or args["data"] or args["amp;data"] or "" local request_content_type = request_headers["content-type"] or "" local response_headers = ngx.resp.get_headers() local response_content_type = response_headers["content-type"] or "" local request_body = "" if request_content_type:match("application/json") then request_body = ngx.var.request_body or "" end local response_body = "" if response_content_type:match("application/json") then response_body = ngx.ctx.response_body or "" end request_headers_json = "" pcall(function() request_headers_json = cjson.encode(request_headers) end) response_headers_json = "" pcall(function() response_headers_json = cjson.encode(response_headers) end) local logger = require "resty.logger.socket" if not logger.initted() then local ok, err = logger.init{ host = "127.0.0.1", port = 39876, sock_type = "tcp", flush_limit = 10240, drop_limit = 1048576, timeout = 1000, max_retry_times = 3, retry_interval = 10000 } if not ok then ngx.log(ngx.ERR, "Logger初始化失败: ", err) return end end local log_data = { access_time = ngx.var.time_iso8601, status = ngx.var.status, request_time = ngx.var.request_time, uri = ngx.var.uri, query_string = query_string, request_body = request_body, request_headers = request_headers_json, response_headers = response_headers_json, response_body = response_body, token = token, request_method = ngx.var.request_method, scheme = ngx.var.scheme, server_protocol = ngx.var.server_protocol, request_length = ngx.var.request_length, body_bytes_sent = ngx.var.body_bytes_sent, bytes_sent = ngx.var.bytes_sent, http_x_real_ip = ngx.var.http_x_real_ip, http_x_forwarded_for = ngx.var.http_x_forwarded_for, remote_addr = ngx.var.remote_addr } local success, result = pcall(cjson.encode, log_data) if not success then print("JSON编码失败: ", result) return end local bytes, err = logger.log(result .. "\n") if err then ngx.log(ngx.ERR, "日志发送失败: ", err) end end