且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ruby中向记录器添加自定义日志级别?

更新时间:2023-02-16 17:58:03

您可以简单地将其添加到Logger类中:

You can simply add to the Logger class:

require 'logger'

class Logger
  def self.custom_level(tag)
    SEV_LABEL << tag 
    idx = SEV_LABEL.size - 1 

    define_method(tag.downcase.gsub(/\W+/, '_').to_sym) do |progname, &block|
      add(idx, nil, progname, &block)
    end 
  end 

  # now add levels like this:

  custom_level 'TRAFFIC'
  custom_level 'ANOTHER-TAG'
end


# using it:

log = Logger.new($stdout)
log.traffic('testing')
log.another_tag('another message here.')