3

I'd like to include the name of the class that invokes the logger in the log output, such as:

[MyClass] here is the message

I've seen the option of using the Contexts but I don't want to have to do something like this throughout my app when I log stuff (keep in mind, I want the class name in every log message):

NDC.push('class:' + self.class.name)
logger.debug 'hello'

I'd like to just call:

logger.debug 'hello'

Any suggestions?

codecraig
  • 3,118
  • 9
  • 48
  • 62

1 Answers1

8

Using the contexts is preferable, but you can use your own formatter (see Log4r formatters)

logger = Logger.new 'test'
outputter = Outputter.stdout
outputter.formatter = PatternFormatter.new(:pattern => "%l - kittens - %m")
logger.outputters = outputter
logger.info 'adorable' # => INFO - kittens - adorable

Or, actually, because you want it to reference self.class my advice would actually to create a Logging module that works like so:

module Logging
  def logger
    return @logger if @logger
    @logger = Logger.new 'test'
    outputter = Outputter.stdout
    outputter.formatter = PatternFormatter.new(:pattern => "%l - #{self.class} - %m")
    @logger.outputters = outputter
    @logger
  end
end

class HasLogging
  include Logging

  def test
    logger.info 'adorable'
  end
end

test = HasLogging.new
test.test # => INFO - HasLogging - adorable

Probably not exactly like that, but you get the idea.

fx_
  • 1,932
  • 13
  • 17
  • That's what I was looking for, although I slightly modified it to set the logger name equal to 'self.class.name' and then use '%C' in the outputter format instead of 'self.class.name' – codecraig Mar 17 '11 at 12:02
  • 1
    That's the spirit. I figured you'd use it in several classes and use the same Logger instance, which wouldn't update the name you set for the Logger. – fx_ Mar 17 '11 at 12:44
  • 1
    This will create a logger for **every class where it is included** and will only work when you are using a module and a method in that module and include that module in a class. The method will be "transferred" into the class and of course when it is called `self.class` returns that class's name. One should not use this solution (but I did not come up with another unfortunately). – phikes Mar 03 '14 at 16:36