我正在尝试从YAML配置文件为活动记录记录器配置debuglevel,但是得到以下错误,除了在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__}"
答案 0 :(得分:1)
可用的日志级别为:: debug,:info,:warn,:error,:fatal, 和:未知,对应于从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)