Log4r - 在日志输出中包含类名

发布于 2024-10-22 18:19:13 字数 402 浏览 4 评论 0原文

我想在日志输出中包含调用记录器的类的名称,例如:

[MyClass] here is the message

我已经看到使用 Contexts 但我不想在记录内容时在整个应用程序中执行类似的操作(请记住,我希望在每条日志消息中都包含类名称):

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

我想打电话:

logger.debug 'hello'

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迟到的我 2024-10-29 18:19:13

最好使用上下文,但您可以使用自己的格式化程序(请参阅 Log4r 格式化程序

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

或者,实际上,因为你希望它引用 self.class 我的建议实际上是创建一个像这样工作的日志模块:

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

可能不完全像那样,但你明白了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文