Ruby on rails 每个环境有多个config.logger

Ruby on rails 每个环境有多个config.logger,ruby-on-rails,papertrail-app,Ruby On Rails,Papertrail App,我使用的是Rails 5,我将应用程序日志发送到我的environments/production.rb config.logger = ActiveSupport::TaggedLogging.new( RemoteSyslogLogger.new( 'logs6.papertrailapp.com', 41364, program: "rails-#{Rails.env}" ) ) 有时将日志发送到papertrail会有延迟,所以我会手动执行tail-f prod

我使用的是Rails 5,我将应用程序日志发送到我的environments/production.rb

config.logger = ActiveSupport::TaggedLogging.new(
  RemoteSyslogLogger.new(
    'logs6.papertrailapp.com', 41364,
    program: "rails-#{Rails.env}"
  )
)
有时将日志发送到papertrail会有延迟,所以我会手动执行
tail-f production.log
,但它不会显示任何内容,因为日志被发送到papertrail

要查看详细日志,我需要将config.logger替换为

config.logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(File.join(Rails.root, "log", "#{Rails.env}.log")))

Rails中有没有一种方法可以在同一环境中使用多个记录器?基本上,我想将日志发送到papertrail或使用尾部日志手动查看日志?

您可以使用自定义日志程序扩展Rails.logger:

syslog_logger = ActiveSupport::TaggedLogging.new(
  RemoteSyslogLogger.new(
    'logs6.papertrailapp.com', 41364,
    program: "rails-#{Rails.env}"
  )
)
Rails.logger.extend(ActiveSupport::Logger.broadcast(syslog_loger))

您可以在初始值设定项文件中或直接在环境配置文件中执行此操作,但您更愿意这样做。

这是一个老问题,但我只是满足了同样的需要,以下是我如何解决此问题的:

  • 已创建LoggerProxy类以将调用转发给多个记录器:
  • 在我的配置文件中,在LoggerProxy中添加了我的两个记录器:

  • @埃尔亚瓦拉多。我试着使用它,但当我使用Rails.logger.extend扩展syslog_记录器时,它不会将日志发送到papertrail,但当我将其分配到production.rb的config.logger时,它会将日志发送到papertrail。
    class LoggerProxy
      def initialize
        @loggers = Set.new
      end
    
      def add(logger)
        @loggers.add(logger)
      end
    
      def remove(logger)
        @loggers.delete(logger)
      end
    
      def method_missing(name, *args, &block)
        @loggers.each do |logger|
          logger.public_send(name, *args, &block)
        end
      end
    end
    
    config.logger = LoggerProxy.new
    config.logger.add(Logger.new(Rails.root.join('log', "#{Rails.env}.log"), 10, 50.megabytes))
    config.logger.add(ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)))