Class: PrettyLogger::RequestLogger

Inherits:
Object
  • Object
show all
Includes:
PrettyLogger
Defined in:
lib/pretty_logger/request_logger.rb

Constant Summary

Constants included from PrettyLogger

COLORS, VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from PrettyLogger

ansi_colors, cl, clean_message, colorize, colors, debug, error, focused_backtrace, info, instance, log, pretty_log, pretty_message, rgb, timestamp, truncate, warn

Constructor Details

#initialize(request: nil, current_user: nil) ⇒ RequestLogger

Returns a new instance of RequestLogger.



5
6
7
8
9
# File 'lib/pretty_logger/request_logger.rb', line 5

def initialize(request:nil, current_user:nil)
  @request = request
  @current_user = current_user
  @data = {}
end

Instance Attribute Details

#current_userObject

Returns the value of attribute current_user.



3
4
5
# File 'lib/pretty_logger/request_logger.rb', line 3

def current_user
  @current_user
end

#dataObject

Returns the value of attribute data.



3
4
5
# File 'lib/pretty_logger/request_logger.rb', line 3

def data
  @data
end

#requestObject

Returns the value of attribute request.



3
4
5
# File 'lib/pretty_logger/request_logger.rb', line 3

def request
  @request
end

Instance Method Details

#log_error(exception) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/pretty_logger/request_logger.rb', line 18

def log_error(exception)
  error([
    "#{pretty_user} #{request.path} #{colorize(:red, exception.class)}",
    params.blank? ? nil : truncate(pretty_message(params)),
    colorize(:red, focused_backtrace(exception.backtrace).first),
    colorize(:red, clean_message("#{exception.class} #{exception.message}")),
  ].compact.join("\n"))
end

#log_request(extra_text = nil) ⇒ Object



11
12
13
14
15
16
# File 'lib/pretty_logger/request_logger.rb', line 11

def log_request(extra_text=nil)
  info([
    "#{pretty_user}#{request.method.upcase} #{request.path} #{extra_text}\e[0m",
    params.blank? ? nil : truncate(pretty_message(params.as_json.deep_symbolize_keys)),
  ].compact.join("\n"))
end

#paramsObject



27
28
29
30
31
# File 'lib/pretty_logger/request_logger.rb', line 27

def params
  return unless @request.present?

  @request.filtered_parameters.except(:action, :controller, :id, :authenticity_token, :_method)
end

#pretty_userObject



33
34
35
36
37
38
39
40
41
# File 'lib/pretty_logger/request_logger.rb', line 33

def pretty_user
  return colorize(:grey, "[?]") unless current_user.present?

  name = current_user.try(:username).presence
  name ||= current_user.try(:name).presence
  name ||= "#{current_user.class.name}:#{current_user.id}"

  colorize(:magenta, "[#{name}]")
end