Ruby: Uninitialized constant Log4r::DEBUG (NameError) problem

给你一囗甜甜゛ 提交于 2019-12-04 12:11:16

This is a little weird. You need to create a logger instance, before you can access the log level constants. Here is how it looks on irb:

>> require "log4r"
=> true
>> Log4r::DEBUG
NameError: uninitialized constant Log4r::DEBUG
    from (irb):2
>> Log4r::Logger.root
=> #<Log4r::RootLogger:0x101737948 @outputters=[], @level=0>
>> Log4r::DEBUG
=> 1
>>

In order to support custom levels the log levels are loaded only when the instance is loaded (arguable whether this is the right approach).

This is the code that actually loads the levels (called from the RootLogger#instance):

Log4r.define_levels(*Log4rConfig::LogLevels)

So in your code you can call it so:

require 'rubygems'
require 'log4r'
require 'log4r/outputter/datefileoutputter' 
Log4r.define_levels(*Log4r::Log4rConfig::LogLevels)
SERVICE_LOG = {
  :log_name         => 'service',
  :log_file         => 'service.log',
  :log_level        => Log4r::DEBUG, 
  :message_pattern  => "[%-5l %d] %C: %M",
  :date_pattern     => "%Y-%m-%d %H:%M:%S"
}

These constants don't seem to exist anymore. What I found was this though:

>> Log4r::Log4rConfig.const_get :LogLevels 
#=> ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"]

Maybe have a look at their examples (e.g. require and include Log4r):

http://log4r.rubyforge.org/manual.html#outofbox

Perhaps you could try something like this

require 'rubygems'
require 'log4r'

L4R = Log4r::Logger.new("Logger")
Log4r::FileOutputter.new('service',
                         :filename=>"service.log",
                         :level=>Log4r::DEBUG)
L4R.add('service')
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!