Sometimes, it’s required to setup Rails logger for storing logs into several backends. In our case we decided to use Loggly, but also wanted to leave old file-based logging.
Despite the actual solution is very simple, it’s hard to find it. The best match on StackOverflow suggests to create some custom proxy class.
Solution
Now with Rails 4 it’s a real no-brainer. Let’s solve a task from SO – add alternative logging into file:
file_logger = Logger.new(Rails.root.join("log/alternative-output.log")) Rails.logger.extend(ActiveSupport::Logger.broadcast(file_logger))
Setting Loggly as additional backend is not much harder:
# using gem 'logglier' loggly = Logglier.new('https://logs.loggly.com/inputs//tag/ruby', threaded: true) Rails.logger.extend(ActiveSupport::Logger.broadcast(loggly))
All you need is to provide object which implements Logger interface for ActiveSupport::Logger.broadcast. In this way, you can add as much logging backends, as you wish.
Rails 3
If you are on Rails 3, just copy original active_support/logger.rb into config/initializers/active_support_logger.rb. Also, remove two lines, which don’t work in Rails 3 environment: line 2 with require ‘active_support/logger_silence’, and line 7 with include LoggerSilence.
Now it can be used as in previous recipes.