Skip to content

Instantly share code, notes, and snippets.

@gregretkowski
Created October 11, 2012 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregretkowski/3873591 to your computer and use it in GitHub Desktop.
Save gregretkowski/3873591 to your computer and use it in GitHub Desktop.
Adding 'trace' to ruby Logger
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"
@neoice
Copy link

neoice commented Jul 11, 2016

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 =>

@veetow
Copy link

veetow commented Apr 28, 2017

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

@cmtonkinson
Copy link

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