Using rails tagged logging, how can I log the log level of a message?
Asked Answered
M

3

9

My rails logger configuration currently logs the current time and UUID, like this:

config.logger = ActiveSupport::TaggedLogging.new(Logger.new("#{Rails.root}/log/#{ENV['RAILS_ENV']}.log", 'daily'))
config.log_tags = [Proc.new {Time.now.strftime('%Y-%m-%d %H:%M:%S.%L')}, :uuid]

Is there a way to also log the current message's log level?

i.e., if I call logger.debug, the tag [DEBUG] is added to the message.

Masterful answered 17/5, 2012 at 1:46 Comment(0)
G
8

Railscasts shows how to override the logger to output the severity of the log message by overriding the SimpleFormatter#call method:

class Logger::SimpleFormatter
  def call(severity, time, progname, msg)
    "[#{severity}] #{msg}\n"
  end
end

See http://railscasts.com/episodes/56-the-logger-revised for the details.

Garlaand answered 12/7, 2012 at 14:57 Comment(0)
B
0

We can't change the msg in which come from database procedure but we can only change the look n feel of logs by showing time and changing it's color and severity.

Use following code to update logs. Paste below code in new file which needs to create at config/initilizers .

class ActiveSupport::Logger::SimpleFormatter
SEVERITY_TO_TAG_MAP     = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
USE_HUMOROUS_SEVERITIES = true

def call(severity, time, progname, msg)
  if USE_HUMOROUS_SEVERITIES
    formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity])
  else
    formatted_severity = sprintf("%-5s",severity)
  end

  formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
  color = SEVERITY_TO_COLOR_MAP[severity]

  "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
end

end

Billington answered 24/11, 2023 at 19:56 Comment(0)
I
-4

I added MyApp::Application.config.log_level to the log tags and it worked for me.

config.log_tags = [Proc.new {Time.now.strftime('%Y-%m-%d %H:%M:%S.%L')}, :uuid, Proc.new {MyApp::Application.config.log_level}]
Ironmaster answered 17/5, 2012 at 8:28 Comment(1)
As far as I understand, that is the minimum log level defined for the application, not the log level of the individual message.Masterful

© 2022 - 2024 — McMap. All rights reserved.