Search code examples
rubylog4r

Log4r - include class name in log output


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?


Solution

  • 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.