Skip to content

Instantly share code, notes, and snippets.

@searls
Last active March 4, 2024 19:18
Show Gist options
  • Save searls/a2a642520b36594bb9002e2f75761eec to your computer and use it in GitHub Desktop.
Save searls/a2a642520b36594bb9002e2f75761eec to your computer and use it in GitHub Desktop.
This logger wrapper I wrote.
# Leverages the BroadcastLogger introduced in Rails 7.1 to wrap the current
# logger in a new logger that broadcasts to both the current logger and $stdout
#
# (Announcement: https://rubyonrails.org/2023/9/29/this-week-in-rails)
#
# If the current logger already broadcasts to $stdout, it will not be wrapped,
# making it safe to call this method multiple times without knowing the current
# logging "sitch".
#
# Usage probably looks something like this:
#
# > Rails.logger = EnsuresLoggerBroadcastsToStdout.new.call(Rails.logger)
#
class EnsuresLoggerBroadcastsToStdout
def call(logger)
loggers = logger.respond_to?(:broadcasts) ? logger.broadcasts : [logger]
if loggers.none? { |logger| logging_to_stdout?(logger) }
ActiveSupport::BroadcastLogger.new(
ActiveSupport::Logger.new($stdout, formatter: Logger::Formatter.new),
*loggers
)
else
logger
end
end
def logging_to_stdout?(logger)
logdev = logger.instance_variable_get(:@logdev)
logdev.respond_to?(:dev) && logdev.dev == $stdout
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment