Class: ConciseLogging::LogSubscriber

Inherits:
ActiveSupport::LogSubscriber
  • Object
show all
Defined in:
lib/concise_logging/log_subscriber.rb

Constant Summary collapse

INTERNAL_PARAMS =
%w(controller action format _method only_path)

Instance Method Summary collapse

Instance Method Details

#compute_status(payload) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/concise_logging/log_subscriber.rb', line 39

def compute_status(payload)
  details = nil
  status = payload[:status]
  if status.nil? && payload[:exception].present?
    exception_class_name = payload[:exception].first
    status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)

    if payload[:exception].respond_to?(:uniq)
      details = payload[:exception].uniq.join(" ")
    end
  end
  [status, details]
end

#format_method(method) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/concise_logging/log_subscriber.rb', line 53

def format_method(method)
  if method.strip == "GET"
    method
  else
    color(method, CYAN)
  end
end

#format_status(status) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/concise_logging/log_subscriber.rb', line 61

def format_status(status)
  status = status.to_i
  if status >= 400
    color(status, RED)
  elsif status >= 300
    color(status, YELLOW)
  else
    color(status, GREEN)
  end
end

#process_action(event) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/concise_logging/log_subscriber.rb', line 9

def process_action(event)
  payload = event.payload
  param_method = payload[:params]["_method"]
  method = param_method ? param_method.upcase : payload[:method]
  status, exception_details = compute_status(payload)
  path = payload[:path].to_s.gsub(/\?.*/, "")
  params = payload[:params].except(*INTERNAL_PARAMS)

  ip = Thread.current[:logged_ip]
  location = Thread.current[:logged_location]
  Thread.current[:logged_location] = nil

  app = payload[:view_runtime].to_i
  db = payload[:db_runtime].to_i

  message = format(
    "%{method} %{status} %{ip} %{path}",
    ip: format("%-15s", ip),
    method: format_method(format("%-6s", method)),
    status: format_status(status),
    path: path
  )
  message << " redirect_to=#{location}" if location.present?
  message << " parameters=#{params}" if params.present?
  message << " #{color(exception_details, RED)}" if exception_details.present?
  message << " (app:#{app}ms db:#{db}ms)"

  logger.warn message
end

#redirect_to(event) ⇒ Object



5
6
7
# File 'lib/concise_logging/log_subscriber.rb', line 5

def redirect_to(event)
  Thread.current[:logged_location] = event.payload[:location]
end