log.lua 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. if ngx.ctx.log_request then
  2. local cjson = require "cjson"
  3. local args = ngx.req.get_uri_args()
  4. local query_string = ""
  5. pcall(function()
  6. query_string = cjson.encode(args)
  7. end)
  8. local request_headers = ngx.req.get_headers()
  9. local token = request_headers["token"] or args["token"] or args["data"] or args["amp;data"] or ""
  10. local request_content_type = request_headers["content-type"] or ""
  11. local response_headers = ngx.resp.get_headers()
  12. local response_content_type = response_headers["content-type"] or ""
  13. local request_body = ""
  14. if request_content_type:match("application/json") then
  15. request_body = ngx.var.request_body or ""
  16. end
  17. local response_body = ""
  18. if response_content_type:match("application/json") then
  19. response_body = ngx.ctx.response_body or ""
  20. end
  21. request_headers_json = ""
  22. pcall(function()
  23. request_headers_json = cjson.encode(request_headers)
  24. end)
  25. response_headers_json = ""
  26. pcall(function()
  27. response_headers_json = cjson.encode(response_headers)
  28. end)
  29. local logger = require "resty.logger.socket"
  30. if not logger.initted() then
  31. local ok, err = logger.init{
  32. host = "127.0.0.1",
  33. port = 39876,
  34. sock_type = "tcp",
  35. flush_limit = 10240,
  36. drop_limit = 1048576,
  37. timeout = 1000,
  38. max_retry_times = 3,
  39. retry_interval = 10000
  40. }
  41. if not ok then
  42. ngx.log(ngx.ERR, "Logger初始化失败: ", err)
  43. return
  44. end
  45. end
  46. local log_data = {
  47. access_time = ngx.var.time_iso8601,
  48. status = ngx.var.status,
  49. request_time = ngx.var.request_time,
  50. uri = ngx.var.uri,
  51. query_string = query_string,
  52. request_body = request_body,
  53. request_headers = request_headers_json,
  54. response_headers = response_headers_json,
  55. response_body = response_body,
  56. token = token,
  57. request_method = ngx.var.request_method,
  58. scheme = ngx.var.scheme,
  59. server_protocol = ngx.var.server_protocol,
  60. request_length = ngx.var.request_length,
  61. body_bytes_sent = ngx.var.body_bytes_sent,
  62. bytes_sent = ngx.var.bytes_sent,
  63. http_x_real_ip = ngx.var.http_x_real_ip,
  64. http_x_forwarded_for = ngx.var.http_x_forwarded_for,
  65. remote_addr = ngx.var.remote_addr
  66. }
  67. local success, result = pcall(cjson.encode, log_data)
  68. if not success then
  69. print("JSON编码失败: ", result)
  70. return
  71. end
  72. local bytes, err = logger.log(result .. "\n")
  73. if err then
  74. ngx.log(ngx.ERR, "日志发送失败: ", err)
  75. end
  76. end