Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple config.logger per environment

Tags:

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?

like image 642
AllenC Avatar asked Apr 27 '18 04:04

AllenC


2 Answers

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.

like image 92
elyalvarado Avatar answered Oct 11 '22 14:10

elyalvarado


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)))
like image 32
Nementon Avatar answered Oct 11 '22 13:10

Nementon