开发者

Log4r - include class name in log output

开发者 https://www.devze.com 2023-02-17 22:18 出处:网络
I\'d like to include the name of the class 开发者_JAVA百科that invokes the logger in the log output, such as:

I'd like to include the name of the class 开发者_JAVA百科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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号