AllenC
AllenC

Reputation: 2754

Multiple config.logger per environment

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?

Upvotes: 5

Views: 2491

Answers (2)

Nementon
Nementon

Reputation: 26

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)))

Upvotes: 1

elyalvarado
elyalvarado

Reputation: 1296

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.

Upvotes: 3

Related Questions