Log4r - include class name in log output

I would like to include a class name that calls the logger in the output log file, for example:

[MyClass] here is the message

I saw a use case for Contexts , but I don’t want to do something like this in my application when I register the material (keep in mind, I want the class name in each log message):

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

I would just call:

logger.debug 'hello'

Any suggestions?

+3
source share
1 answer

Using 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, in fact, because you want it to refer to self.class, my advice is actually to create a log module that works like this:

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 quite so, but you get the point.

+8
source

All Articles