Home Ruby grape 使用logger
Post
Cancel

Ruby grape 使用logger

用了Grape之后,才发现,这个东东是默认没有日志的.所以就看不到 每次请求耗费多长时间 ( Completed in xxx ms )

所以,有个Gem:  https://github.com/aserafin/grape_logging

1. Gemfile: 

gem 'grape_logging'

2. 在每个grape API的方法前面,都要加上:

 module APIv2
   class Members < Grape::API
      # 下面两行,是 对 grape logger进行配置
    use GrapeLogging::Middleware::RequestLogger,
      instrumentation_key: 'my_grape_key'

3. 在 config/initializers/grape_logger.rb 中,增加内容: 

ActiveSupport::Notifications.subscribe('my_grape_key') do |name, starts, ends, notification_id, payload|
  Rails.logger.info payload
end

这样,grape就可以跟rails结合了, 我们可以看到新的日志如下: 

13:02:25 INFO: Started GET "/api/v2/members/me?public_key=123456&signature=d17f01cacab129355f2c6d777aa4a457&nonce=333&a=1&b=2&d=&g=" for 127.0.0.1 at 2018-06-04 13:02:25 +0800
......
13:02:25 INFO: {:status=>200, :time=>{:total=>100.88, :db=>7.6, :view=>93.28}, :method=>"GET", :path=>"/api/v2/members/me", :params=>{"public_key"=>"123456", "signature"=>"d17f01cacab129355f2c6d777aa4a457",
"nonce"=>"333", "a"=>"1", "b"=>"2", "d"=>"", "g"=>""}, :host=>"localhost"}

This post is licensed under CC BY 4.0 by the author.