简体   繁体   English

如何在可执行文件中加载Rails.logger?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM