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

回眸只為那壹抹淺笑 提交于 2020-01-01 16:45:13

问题


While using log4r in Ruby, I wrote a configuration file similar to the following:

  require 'rubygems'
  require 'log4r'
  require 'log4r/outputter/datefileoutputter' 
  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"
  }

when I ran it, it threw out the following exception:

 C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:440:in `load_missing_constant': uninitialized constant Log4r::DEBUG (NameError)

Why did it do that?


回答1:


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"
}



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/5799823/ruby-uninitialized-constant-log4rdebug-nameerror-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!