5

I'm using Rails 5 and I'm sending application logs to papertrail using this snippet on my environments/production.rb

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

Sometimes there's a delay sending out the logs to papertrail so I do tail -f production.log manually but it doesn't show anything since the logs were being sent to papertrail.

To view tailed logs I need to replace the config.logger with

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

Is there a way in Rails I can use multiple logger in the same environment? Basically I want to send logs to papertrail or view logs manually using tailed logs?

AllenC
  • 2,754
  • 1
  • 41
  • 74

2 Answers2

3

You can extend the Rails.logger with your custom logger:

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

You can do that in an initializer file, or directly on your environment config file, however you prefer to do it.

elyalvarado
  • 1,226
  • 8
  • 13
  • @elyavarado. I tried to use this but when I extend the syslog_logger using Rails.logger.extend it doesn't send logs to papertrail, but when I assign it to config.logger of production.rb it sends the logs to papertrail. – AllenC Apr 30 '18 at 09:21
1

Kinda old question, but I just meet the same need, here how I've resolved it:

  1. Created a LoggerProxy class to forward call to multiple loggers:
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
  1. In my configuration file, added my two loggers in the LoggerProxy:
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)))
Nementon
  • 26
  • 2