Hatchet includes a Railtie that is loaded automatically and wraps the
Add this line to your application’s Gemfile to get Hatchet from RubyGems.org:
And then execute:
To make it so your log calls are scoped to your controllers you also need to add
Hatchet to your
class ApplicationController < ActionController::Base include Hatchet end
You could include it in your models so that each of those has its own logging context too.
By default the Railtie will wrap the standard Rails logger. If you want to
utilize some of the more advanced functionality of Hatchet it is recommended
that you place your configuration into
Before specifying your custom configuration you may want to reset Hatchet in order to remove the Rails logger from its configuration:
Hatchet.configure do |config| # Remove any existing configuration config.reset! # Then specify your custom configuration end
You can also specify configuration in the standard
the corresponding environment-specific configuration files (such as
The Hatchet configuration is available through
config.hatchet. If you are
setting just one property you can access it directly:
However, if you want to specify multiple values it will read better if you use the block form:
config.hatchet.configure do |hatchet| hatchet.level :error hatchet.formatter = SimpleFormatter.new hatchet.appenders << CustomAppender.new end
There are some special considerations when using Hatchet with Heroku. Heroku
doesn’t have a file system so adds the
rails_log_stdout plugin for you.
rails_log_stdout monkey patches the Rails logger meaning Hatchet
cannot hook into it as it can in normal environments.
“I don’t care about the backstory, how do I get Hatchet to work with Heroku?” I’m glad you asked.
At the terminal within your application’s root directory:
$ mkdir -p vendor/plugins/rails_log_stdout $ touch vendor/plugins/rails_log_stdout/.gitkeep $ git commit -am "Prevent Heroku adding rails_log_stdout"
This stops the Heroku application packaging process from adding the
rails_log_stdout plugin on your behalf.
Add the following configuration to your
config.hatchet.configure do |hatchet| # Reset the logging configuration hatchet.reset! # Use the format without time, etc so we don't duplicate it hatchet.formatter = Hatchet::SimpleFormatter.new # Set up a STDOUT appender hatchet.appenders << Hatchet::LoggerAppender.new do |appender| appender.logger = Logger.new(STDOUT) end end
This removes any previous configuration (such as the default Rails logger that
will to write to a file) and then adds an appender writing to STDOUT. The use of
SimpleFormatter is just a suggestion, you are of course free to use any
formatter you want.
Usually STDOUT batches lines together when writing as it writes them out
asynchronously. This can be a bit rubbish with logs so you need to force it to
write synchronously. I usually put this into my
STDOUT.sync = true