You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
5.2 KiB

2 months ago
  1. module Semantic
  2. module Subscribers
  3. # LogSubscriber for event_group :action_controller
  4. class ActionController < LogSubscriber
  5. include AnsiColors
  6. INTERNAL_PARAMS = %i[controller action format _method only_path].freeze
  7. DEFAULT_DEV_HOSTS = ['127.0.0.1', 'localhost'].freeze
  8. TERMINUS_STRING = '╙─╜'.freeze
  9. def initialize(session_key)
  10. super(:controller)
  11. @session_key = session_key
  12. @transactions = {}
  13. end
  14. def start_processing(event)
  15. session_value = session_value(event)
  16. @transactions[event.transaction_id] = session_value # preserve session_value to help finish_processing
  17. SemanticLogger.tagged(session_value) do
  18. request = event.payload[:request]
  19. path = colorize(request.filtered_path, BOLD)
  20. dimensions = Semantic::FancyDimensions.new(rails: '╓─╖', before: 1)
  21. if defined?(@previously_redirect) && @previously_redirect
  22. dimensions = Semantic::FancyDimensions.new(rails: '╓║╖', before: 0)
  23. @previously_redirect = false
  24. end
  25. logger.info("Started #{request.raw_request_method} #{path}", dimensions:)
  26. format = event.payload[:format]
  27. format = format.to_s.upcase if format.is_a?(Symbol)
  28. format = '*/*' if format.nil?
  29. format = colorize(format, BOLD)
  30. logger.debug("Processing by #{event.payload[:controller]}##{event.payload[:action]} as #{format}")
  31. params = event.payload[:params].deep_symbolize_keys.except(*INTERNAL_PARAMS)
  32. unless params.empty?
  33. params = params.ai(ruby19_syntax: true, plain: true, multiline: false)
  34. params.gsub!(/(\w+):/, "#{TEXT_CYAN}\\1#{CLEAR}:")
  35. params.gsub!(/"(.*?)"/, "\"#{TEXT_YELLOW}\\1#{CLEAR}\"")
  36. end
  37. logger.debug("Parameters: #{params}") unless params.empty?
  38. end
  39. end
  40. def process_action(event)
  41. session_value = @transactions.delete(event.transaction_id) # delete previous session_value from start_processing
  42. SemanticLogger.tagged(session_value) do
  43. payload = event.payload
  44. additions = ::ActionController::Base.log_process_action(payload)
  45. status = payload[:status]
  46. if status.nil? && (exception_class_name = payload[:exception]&.first)
  47. status = ::ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
  48. end
  49. additions << pop_active_record_summary
  50. additions << "GC: #{event.gc_time.round(1)}ms"
  51. additions.compact!
  52. if event.duration >= 1200
  53. logger.error process_duration(event, additions)
  54. elsif event.duration >= 600
  55. logger.warn process_duration(event, additions)
  56. elsif event.duration >= 300
  57. logger.info process_duration(event, additions)
  58. # elsif event.duration >= 100
  59. else
  60. logger.debug process_duration(event, additions)
  61. end
  62. status_family = status / 100
  63. dimensions = case status_family
  64. when 2
  65. Semantic::FancyDimensions.new(rails: TERMINUS_STRING)
  66. when 3, 5
  67. Semantic::FancyDimensions.new(rails: '╙║╜')
  68. when 4
  69. Semantic::FancyDimensions.new(rails: '╙╨╜')
  70. end
  71. logger.info("Completed #{colorize(status, BOLD)} #{Rack::Utils::HTTP_STATUS_CODES[status]}", dimensions:)
  72. logger.info(' ', dimensions: Semantic::FancyDimensions.new(rails: ' ║ ')) if status_family == 3
  73. logger.info(' ', dimensions: Semantic::FancyDimensions.new(rails: '╓║╖')) if status_family == 5
  74. end
  75. end
  76. def redirect_to(event)
  77. location = capture_path(event.payload[:location])
  78. logger.debug("Redirected to #{colorize(location, BOLD)}")
  79. @previously_redirect = true
  80. end
  81. private
  82. # FIXME: might be more accurate, multiple transactions, sum of CRUD
  83. def pop_active_record_summary
  84. active_record_transactions = Thread.current[ActiveRecord.to_s]
  85. return unless active_record_transactions
  86. # reset thread local
  87. Thread.current[ActiveRecord.to_s] = nil
  88. active_record_transactions.map do |k, art|
  89. art.except(:total_duration)
  90. .select { |_, value| value.positive? }
  91. .map { |k, v| "#{v} #{k.to_s.pluralize(v)}" }
  92. .join(',')
  93. end.compact.join('|')
  94. end
  95. def redirect_regex
  96. return @redirect_regex if defined?(@redirect_regex)
  97. options = Rails.application.routes.default_url_options
  98. dev_hosts = DEFAULT_DEV_HOSTS + Array.wrap(options[:host])
  99. dev_hosts_or = dev_hosts.uniq.join('|')
  100. dev_from = "http://(?:#{dev_hosts_or}):#{options[:port]}(.*)"
  101. @redirect_regex = /^#{dev_from}/
  102. end
  103. def capture_path(url)
  104. m = redirect_regex.match(url)
  105. m.nil? ? url : m[1]
  106. end
  107. def session_value(event) = event.payload[:headers]['rack.session'].fetch(@session_key, nil)
  108. def process_duration(event, additions) = "Processed in #{event.duration.round}ms (#{additions.join(' | ')})"
  109. end
  110. end
  111. end