在 rake 任务中使用 rails 记录器,rails 5
Using rails logger in rake tasks, rails 5
我正在 rails 应用程序上构建一个 ruby,使用 rails 5,我有许多 rake 任务,我想从中记录信息。但是,当我尝试访问记录器时,出现错误:undefined local variable or method `logger'
我在 lib/tasks 中有我的 rake 任务,并且我在 production.rb 和 developement.rb
中都声明了一个记录器
这是一个示例任务:
namespace :some_namespace do
desc "a description"
task :scrape_info do
include Scraper
startTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Beginning scrape: #{startTime} " }
Scraper.scrape_info
endTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Finished scrape: #{endTime} " }
end
end
以及 development.rb 中我定义记录器的摘录:
config.logger = Logger.new(STDOUT)
config.log_level = :info
config.logger = ActiveSupport::TaggedLogging.new(logger)
知道如何将记录器合并到 rake 任务中吗?我知道我可以简单地使用 puts 语句打印到标准输出,但最终我想要每天的日志文件,我希望我的 rake 任务包含在这些文件中
答案:
只需添加@Joel_Blum 的答案中给出的环境标签。此外,在 development.rb 中,行
config.logger = ActiveSupport::TaggedLogging.new(logger)
需要:
config.logger = ActiveSupport::TaggedLogging.new(config.logger)
尝试添加环境,这会加载您的 rails 应用。
task :scrape_info => :environment do
...
end
我正在 rails 应用程序上构建一个 ruby,使用 rails 5,我有许多 rake 任务,我想从中记录信息。但是,当我尝试访问记录器时,出现错误:undefined local variable or method `logger'
我在 lib/tasks 中有我的 rake 任务,并且我在 production.rb 和 developement.rb
中都声明了一个记录器这是一个示例任务:
namespace :some_namespace do
desc "a description"
task :scrape_info do
include Scraper
startTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Beginning scrape: #{startTime} " }
Scraper.scrape_info
endTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Finished scrape: #{endTime} " }
end
end
以及 development.rb 中我定义记录器的摘录:
config.logger = Logger.new(STDOUT)
config.log_level = :info
config.logger = ActiveSupport::TaggedLogging.new(logger)
知道如何将记录器合并到 rake 任务中吗?我知道我可以简单地使用 puts 语句打印到标准输出,但最终我想要每天的日志文件,我希望我的 rake 任务包含在这些文件中
答案: 只需添加@Joel_Blum 的答案中给出的环境标签。此外,在 development.rb 中,行
config.logger = ActiveSupport::TaggedLogging.new(logger)
需要:
config.logger = ActiveSupport::TaggedLogging.new(config.logger)
尝试添加环境,这会加载您的 rails 应用。
task :scrape_info => :environment do
...
end