0

我正在尝试从 YAML 配置文件为活动记录记录器配置调试级别,但出现以下错误,除了在 YAML 中使用数字之外,我还能如何做到这一点?

sample.rb:30 warning: toplevel constant LEVEL referenced by Logger::LEVEL
"DEBUG"
ArgumentError: comparison of Fixnum with String failed

这是sample.rb

require 'java'
require 'active_record'
require 'activerecord-jdbc-adapter'
require 'yaml'
require 'logger'

def get_jar_path
  if __FILE__[/.+\.jar!/] #in case run from JAR
    scriptpath = __FILE__[/(.*)\/.+\.jar!/]
    $1[6..-1]
  else #in case run with jRuby
    '..'
  end
end

def load_config
  path = "#{get_jar_path}/#{File.basename(__FILE__, ".*")}.configuration.yml"
  p path
  $conf = YAML::load_file(path)
end

load_config
LEVEL = $conf['debug_level'] #string 'DEBUG' from configuration file
$log = Logger.new( "#{get_jar_path}/log_#{Time.now.strftime("%Y%m%d")}.txt", 'monthly' )
ActiveRecord::Base.logger = $log
ActiveRecord::Base.logger.level = Logger::DEBUG #works
ActiveRecord::Base.logger.level = Logger::LEVEL #doesn't work
p ActiveRecord::Base.logger.level
$log.info "start #{__FILE__}"
4

1 回答 1

1

可用的日志级别有::debug、:info、:warn、:error、:fatal 和:unknown,分别对应从 0 到 5 的日志级别编号。

http://guides.rubyonrails.org/debugging_rails_applications.html

require 'logger'

puts Logger::DEBUG

--output:--
0


str = "DEBUG"
puts Logger.const_get(str)

--output:--
0

因此,您应该执行以下操作:

level = $conf['debug_level'] #string 'DEBUG' from configuration file
$log = Logger.new( "#{get_jar_path}/log_#{Time.now.strftime("%Y%m%d")}.txt", 'monthly' )
ActiveRecord::Base.logger = $log
ActiveRecord::Base.logger.level = Logger.const_get(level)

我不确定您为什么认为在当前范围内定义一个常量 LEVEL 会使该常量出现在 Logger 范围内,以便您可以编写 Logger::LEVEL。你基本上是这样做的:

MYCONST = "hello"

module SomeModule
  SOMECONST = "goodbye"
end

你可以写:

puts MYCONST   #=>hello

..你可以写:

puts SomeModule::SOMECONST  #goodbye

..但你不能写:

puts SomeModule::MYCONST

--output:--
1.rb:10:in `<main>': uninitialized constant SomeModule::MYCONST (NameError)
于 2013-08-28T08:21:15.333 回答