LoginSignup
12
11

More than 5 years have passed since last update.

Rails + Grapeでリクエストログ(実行時間、パラメータ)を出力する

Last updated at Posted at 2016-07-15

やりたいこと

普通Railsではログに

I, [2016-07-15T10:03:39.554712 #7157]  INFO -- : Completed 200 OK in 18ms (Views: 6.1ms | ActiveRecord: 10.3ms)

のように実行時間が残るが、Grapeと組み合わせるとこれが出なくなってしまう。
これを出すようにしたい。ついでにGETやPOSTのパラメータも残したい。

本記事の手順でgrape_loggingを導入すると下記のようなログが出せるようになる。

[INFO] {:status=>201, :time=>{:total=>8.21, :db=>0.0, :view=>8.21}, :method=>"POST", :path=>"/api/moge", :params=>{"a"=>"123"}, :response=>["143"]}

ちなみに、Rails+Grapeでは普通にlogger.debug("hoge")と書くと

undefined local variable or method `logger' 

とエラーになってしまうが、Rails.logger.debug("hoge")と書けばよい。

環境

  • Rails 4.2.6
  • Grape 0.16.2

手順

Gemfileに追記:

gem 'grape_logging'

config/initializers/instrumentation.rbを新規作成:

config/initializers/instrumentation.rb
# Subscribe to grape request and log with Rails.logger
ActiveSupport::Notifications.subscribe('grape_key') do |name, starts, ends, notification_id, payload|
  Rails.logger.info payload
end

自分のAPIクラスに記述:

require 'grape_logging'

class MyAPI < Grape::API
  # https://github.com/aserafin/grape_logging#logging-via-rails-instrumentation
  use GrapeLogging::Middleware::RequestLogger,
      instrumentation_key: 'grape_key',
      include: [ GrapeLogging::Loggers::Response.new,
                GrapeLogging::Loggers::FilterParameters.new ]

  format :json
  content_type :json, "application/json; charset=utf-8"

  # テスト用API
  params do
    requires :a, type: Integer
  end
  post 'moge' do
    20 + params[:a]
  end
end

出力項目をカスタマイズする

レスポンスを全部ロギングするのはさすがに過剰なので出力しないようにしたい。そんな場合は自分のAPIクラスに書いたinclude:の部分からGrapeLogging::Loggers::Response.newを消せば良い。

他にもClientEnvRequestHeadersといった出力項目がある。

    include: [ GrapeLogging::Loggers::Response.new,
               GrapeLogging::Loggers::FilterParameters.new,
               GrapeLogging::Loggers::ClientEnv.new,
               GrapeLogging::Loggers::RequestHeaders.new ]

参考

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11