[英]How to load Rails.logger in an executable file?
I have an executable file in my rails app, bin/log_data
. 我的rails应用程序中有一个可执行文件
bin/log_data
。 In this file, in order to have access to Rails.logger
I have to require the following files: 在此文件中,为了访问
Rails.logger
我需要以下文件:
APP_PATH = File.expand_path('../config/application', __dir__)
require 'rails/commands'
This loads the entire rails environment in this one process that runs bin/log_data
, and I think the approach is a bit heavy handed. 这将在运行
bin/log_data
这一过程中加载整个rails环境,我认为这种方法有点繁重。 Can anyone share with me how I would just load Rails.logger
so that I can do `Rails.logger.info('something relatively important to log')? 谁能和我分享我如何加载
Rails.logger
以便我可以执行Rails.logger.info(“对日志而言相对重要的事情”)?
Also, just some background info, I want to user Rails.logger
because the output goes to log/development.log
which is important for what I want to log to be seen in my heroku logs when I tail my app. 另外,我只想提供一些背景信息,因为我的用户想要使用
Rails.logger
因为输出将输出到log/development.log
,这对于我想要记录的内容非常重要,当我拖尾我的应用程序时,该记录可以在heroku日志中看到。
You can just create an ActiveSupport::Logger
instance: 您可以只创建一个
ActiveSupport::Logger
实例:
require 'active_support/logger'
APP_PATH = File.expand_path('../config/application', __dir__)
rails_env = ENV["RAILS_ENV"] || "development"
logger = ActiveSupport::Logger.new(APP_PATH + "/logs/#{rails_env}.log")
If you really want to call it as Rails.logger
create a module: 如果您真的想将其称为
Rails.logger
创建一个模块:
require 'active_support/logger'
require 'active_support/string_inquirer'
APP_PATH = File.expand_path('../config/application', __dir__)
logger = ActiveSupport::Logger.new(APP_PATH + "/logs/#{rails_env}.log")
module Rails
class << self
attr_reader :logger
attr_reader :env
end
self.env = ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || "development")
self.logger = ActiveSupport::Logger.new(APP_PATH.join("logs", "#{self.env}.log"))
end
Note that it will not have the exacts same setting as the Rails logger when it comes to log levels and formatting which only really can be obtained by starting the rails app. 请注意,在日志级别和格式方面,它的设置与Rails记录器的设置完全不同,只有通过启动Rails应用程序才能真正获得该设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.