【问题标题】:active_record configuration from yaml file: debuglevel来自 yaml 文件的 active_record 配置:debuglevel
【发布时间】:2023-03-15 14:45:02
【问题描述】:

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

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

这里是示例.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__}"

【问题讨论】:

    标签: ruby activerecord logging jruby yaml


    【解决方案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)
    

    【讨论】:

    猜你喜欢
    • 2016-02-05
    • 2020-02-16
    • 1970-01-01
    • 2020-05-07
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多