Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

log4r

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?

like image 629
ywenbo Avatar asked Apr 08 '26 18:04

ywenbo


1 Answers

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"
}
like image 193
Swanand Avatar answered Apr 11 '26 08:04

Swanand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!