logs_http_access.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module ApplicationController::LogsHttpAccess
  2. extend ActiveSupport::Concern
  3. included do
  4. after_action :http_log
  5. end
  6. private
  7. def http_log_config(config)
  8. @http_log_support = config
  9. end
  10. # log http access
  11. def http_log
  12. return if !@http_log_support
  13. # request
  14. request_data = {
  15. content: '',
  16. content_type: request.headers['Content-Type'],
  17. content_encoding: request.headers['Content-Encoding'],
  18. source: request.headers['User-Agent'] || request.headers['Server'],
  19. }
  20. request.headers.each do |key, value|
  21. next if key[0, 5] != 'HTTP_'
  22. request_data[:content] += if key == 'HTTP_COOKIE'
  23. "#{key}: xxxxx\n"
  24. else
  25. "#{key}: #{value}\n"
  26. end
  27. end
  28. body = request.body.read
  29. if body
  30. request_data[:content] += "\n" + body
  31. end
  32. request_data[:content] = request_data[:content].slice(0, 8000)
  33. # response
  34. response_data = {
  35. code: response.status = response.code,
  36. content: '',
  37. content_type: nil,
  38. content_encoding: nil,
  39. source: nil,
  40. }
  41. response.headers.each do |key, value|
  42. response_data[:content] += "#{key}: #{value}\n"
  43. end
  44. body = response.body
  45. if body
  46. response_data[:content] += "\n" + body
  47. end
  48. response_data[:content] = response_data[:content].slice(0, 8000)
  49. record = {
  50. direction: 'in',
  51. facility: @http_log_support[:facility],
  52. url: url_for(only_path: false, overwrite_params: {}),
  53. status: response.status,
  54. ip: request.remote_ip,
  55. request: request_data,
  56. response: response_data,
  57. method: request.method,
  58. }
  59. HttpLog.create(record)
  60. end
  61. end