How to add a custom log level to logger in ruby?

后端 未结 6 387

I need to add a custom log level like \"verbose\" or \"traffic\" to ruby logger, how to do?

6条回答
  •  囚心锁ツ
    2021-01-11 16:07

    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.')
    

提交回复
热议问题