Logging Grape API calls with Graylog2
Out Of Date Warning
This article was published on 21/08/2014, this means the content may be out of date or no longer relevant.
You should verify that the technical information in this article is still up to date before relying upon it for your own purposes.
We are using Graylog2 together with Rails to provide a central logging platform for all of our Rails applications. Unfortunately, Grape, a popular API builder written in Ruby, has no automatic configuration for logging to Graylog.
We are initializing the Graylog2 logger in the config/environments/production.rb
:
app_name ||= config.action_mailer.default_url_options.try(:fetch, :host) || Rails.application.class.name.underscore.split('/').tap{|i|i.pop}.join('/')
config.logger = GELF::Logger.new("logging.example.com", 12201, "WAN", { :host => app_name, :environment => Rails.env })
Here is a snippet, which solves the logging issue when put into the Grape classes:
class SomeApi < Grape::Api
before do
@start = Time.now.to_f
end
after do
duration = (Time.now.to_f - @start) * 1000
logger = Rails.configuration.logger
logger ||= Rails.logger
logger.info({
short_message: "[#{status}] #{request.request_method} #{request.path}",
code: status,
ip: request.ip,
user_agent: request.user_agent,
params: request.params.except('route_info').to_hash,
duration: duration.to_i,
session: request.session.except('session_id', '_csrf_token').to_hash
})
end
# ...
end
Note: The solution above won't log exceptions. We don't track exceptions through Graylog but using the Airbrake/Errbit combo.
Note 2: I already blogged about, how to make Graylog work with Rails.