Created
October 11, 2012 16:25
-
-
Save gregretkowski/3873591 to your computer and use it in GitHub Desktop.
Adding 'trace' to ruby Logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'logger' | |
# Monkeypatch a 'trace' loglevel into ruby Logger | |
class Logger | |
module Severity; TRACE=-1;end | |
def trace(progname = nil, &block);add(TRACE, nil, progname, &block);end | |
def trace?; @level <= TRACE; end | |
end | |
l = Logger.new(STDERR) | |
l.level = Logger::TRACE | |
l.info "info message" | |
l.trace "trace message" |
You can further the monkeypatch by redefining the SEV_LABEL constant to be a Hash (can't use Array because TRACE is -1):
Logger::SEV_LABEL = {
-1 => 'TRACE',
0 => 'DEBUG',
1 => 'INFO',
2 => 'WARN',
3 => 'ERROR',
4 => 'FATAL',
5 => 'ANY'
}
l = Logger.new(STDOUT)
l.level = Logger::TRACE
l.trace('tracing')
T, [2017-04-27T20:43:00.110077 #42359] TRACE -- : tracing
I combined both of the above techniques with one caveat - before @veetow's solution would work I had to undefine Logger::SEV_LABEL
. Ruby (v2.4.1.p111) wouldn't let me modify or overwrite it otherwise, since it's a constant. My full solution:
# Monkeypatch the STDLIB Logger class with an additional verbosity
# level under DEBUG called TRACE.
require 'logger'
class Logger
self.send :remove_const, 'SEV_LABEL'
SEV_LABEL = {
-1 => 'TRACE',
0 => 'DEBUG',
1 => 'INFO',
2 => 'WARN',
3 => 'ERROR',
4 => 'FATAL',
5 => 'ANY'
}.freeze
module Severity
TRACE = -1
end
def trace(progname = nil, &block)
add(TRACE, nil, progname, &block)
end
def trace?
@level <= TRACE
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a bunch of people tried answering this question on StackOverflow and your answer seems to be far superior to any of those.
the severity printed as a string is incorrect for me though :(
A, [2016-07-11T09:54:48.666155 #6597] ANY -- : [-] raw output =>