开发者

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

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)

开发者_StackOverflow社区Why did it do that?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜