我使用此设置了以下内容:Ruby - share logger instance among module/classes
编辑:根据以下评论,我更新了代码但仍然存在登录问题。
module Logging
# in classes needing to be logged use 'include Logger'
require 'logger'
require 'remote_syslog_logger'
require_relative 'env'
class << self
def logger
return @logger if @logger
if ENV['ENVIRONMENT'] == 'production' #may need to change this
@logger ||= Logger.new($stdout)
@logger.level = Logger::WARN
@logger.datetime_format = "%N "
elsif ENV['ENVIRONMENT'] == 'development'
binding.pry
#$logger = Logger.new(STDOUT)
@logger = RemoteSyslogLogger.new('logs2.papertrailapp.com',39257)
@logger.level = Logger::DEBUG
@logger.datetime_format = "%N "
end
end
def logger=(logger)
@logger = logger
end
end
# Addition
def self.included(base)
class << base
def logger
Logging.logger
end
end
end
def logger
Logging.logger
end
end
我如何记录:
class CronCheck
require_relative 'module_logger.rb'
include Logging
def self.run
begin
logger.debug "**** running cron_check_schedule.rb #{Time.now} #{Time.now.to_i}****"
rescue
end
end
问题:如何修改模块以便可以定义一次这种类型的逻辑,而我所要做的就是为所有类和方法传递一个ENV值以同样的方式登录? /强>
我在logger.debug中遇到错误:未定义的方法`debug&#39; for&#34;%N&#34;:String
答案 0 :(得分:0)
假设第一个片段是module Logging
,您认为包含在任何地方进行日志记录(否则全局变量就像在第二个片段中完全开箱即用),您只需根据片段#2初始化记录器:
# this is the topmost method from your snippet #1,
# updated to use env settings for logger tuning
def logger
# @logger ||= Logger.new($stdout)
return @logger if @logger
@logger = case ENV['ENVIRONMENT']
when 'production'
Logger.new(STDOUT).tap do |logger|
logger.level = Logger::WARN
logger.datetime_format = "%N "
end
else
.......
end
end
就是这样。
答案 1 :(得分:0)
您的代码几乎完全正确。但是,您需要设置的是Logging.logger
,而不是$logger
:
def self.instantiate_logger
logger = Logger.new(STDOUT)
logger.datetime_format = "%N "
if ENV['ENVIRONMENT'] == 'production'
logger.level = Logger::WARN
elsif ENV['ENVIRONMENT'] == 'development'
logger.level = Logger::DEBUG
end
Logging.logger = logger
end
从您的问题中不清楚这种方法的存在方式,但它应该是您在应用初始化过程中可以调用的地方。
您注意到我删除了与Pry相关的代码;由于该代码与日志记录没有直接关系,因此它可能应该转移到其他地方。
但是,我会再做一点改进,通过将日志级别放入由各自环境键入的哈希值来使其更具说明性:
LOG_LEVELS = {
"production" => Logger::WARN,
"development" => Logger::DEBUG
}
def self.instantiate_logger
Logging.logger = Logger.new(STDOUT).tap do |logger|
logger.datetime_format = "%N "
logger.level = LOG_LEVELS[ENV['ENVIRONMENT']] || LOG_LEVELS["development"]
end
end