Using the ActiveSupport::BroadcastLogger

Posted . Visible to the public.

The ActiveSupport::BroadcastLogger Show archive.org snapshot allows you to log to multiple sinks. You know this behavior from from the rails server command, that both logs to standard out and the log/development.log file.

Here is an example from the ActiveSupport::BroadcastLogger API:

stdout_logger = ActiveSupport::Logger.new(STDOUT)
file_logger = ActiveSupport::Logger.new("development.log")
broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger)

broadcast.info("Hello world!") # Writes the log to STDOUT and the development.log file.

Here is an example for Sidekiq:

Sidekiq.configure_client do |config|
  if ENV['RAILS_ENV'] == 'development' || ENV['RAILS_ENV'] == 'test'
    stdout_logger = ActiveSupport::Logger.new(STDOUT)
    file_logger = ActiveSupport::Logger.new("log/sidekiq_#{ENV['RAILS_ENV']}.log")
    broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger)
    broadcast.level = Logger::INFO

    config.logger = broadcast
  end
end

Sidekiq.configure_server do |config|
   if ENV['RAILS_ENV'] == 'development' || ENV['RAILS_ENV'] == 'test'
    stdout_logger = ActiveSupport::Logger.new(STDOUT)
    file_logger = ActiveSupport::Logger.new("log/sidekiq_#{ENV['RAILS_ENV']}.log")
    broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger)
    broadcast.level = Logger::INFO

    config.logger = broadcast
  end
end

Legacy note

In previous versions of ActiveSupport the code for the examples above would have looked like this.

stdout_logger = ActiveSupport::Logger.new(STDOUT)
file_logger = ActiveSupport::Logger.new("development.log")
broadcast = stdout_logger.extend(ActiveSupport::Logger.broadcast(file_logger))

broadcast.info("Hello world!") # Writes the log to STDOUT and the development.log file.
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2024-10-14 08:23)