rails-config

Rails logging into several backends

| 2 Comments

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:

Setting Loggly as additional backend is not much harder:

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.

Share
* Railsware is a premium software development consulting company, focused on delivering great web and mobile applications. Learn more about us.
  • nicki_bee

    Thanks this is exactly what I need. I am a ruby on rails newbie though and am having some issues as when I try to use ActiveSupport::Logger.broadcast(file_logger) in my environment specific config files (i.e. development.rb) i get an error uninitialized constant. Reading up on this it seems these are loaded before the initializers which is I guess why this happens. Is there any way to make sure this class is loaded first? Thanks in advance

    • nicki_bee

      In case anyone also needs to do this, i realised i could wrap this in config.after_inititialize and that did the trick

Want to get more of Railsware blog?

RSS FEED

We're always ready to help!

CONTACT US