I need to add a custom log level like "verbose" or "traffic" to ruby logger, how to do?
There isn't a easy way without write a lot of code?
turri
2010-02-17 14:56:38
@turri not that I know of. It looks like the levels are pretty much coded in ( Logger::INFO and so on). Maybe there's another way but I can't think of it right now
marcgg
2010-02-17 15:18:59
A:
Log levels are nothing but integer constants defined in logger.rb
:
# Logging severity.
module Severity
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
UNKNOWN = 5
end
You can log messages with any level you like using Logger#add
method:
l.add 6, 'asd'
#=> A, [2010-02-17T16:25:47.763708 #14962] ANY -- : asd
Mladen Jablanović
2010-02-17 15:33:40
A:
Your own logger just need to overwrite the Logger#format_severity
method, something like this :
class MyLogger < Logger
SEVS = %w(DEBUG INFO WARN ERROR FATAL VERBOSE TRAFFIC)
def format_severity(severity)
SEVS[severity] || 'ANY'
end
def verbose(progname = nil, &block)
add(5, nil, progname, &block)
end
end
Lucas
2010-02-17 16:30:01
+1
A:
You can simply add to the Logger class:
require 'logger'
class Logger
def self.custom_level(tag)
SEV_LABEL << tag
idx = SEV_LABEL.size - 1
define_method(tag.downcase.gsub(/\W+/, '_').to_sym) do |progname, &block|
add(idx, nil, progname, &block)
end
end
# now add levels like this:
custom_level 'TRAFFIC'
custom_level 'ANOTHER-TAG'
end
# using it:
log = Logger.new($stdout)
log.traffic('testing')
log.another_tag('another message here.')
six364
2010-02-18 22:13:55