新手问题 Grape 如何统计接口调用次数、来源等信息?

scott · October 08, 2013 · Last by vode replied at September 25, 2014 · 5561 hits

使用 grape 做 api,现在想统计每个接口调用次数、来源等信息。找了一圈没有发现有和 grape 搭配使用的 gem,大家是怎么做的呢?

能否写个 helper,然后每次调用前统计一下

使用某种类似 拦截器 的机制不知道能不能行

写个 rack middleware

@zhangyuan 详细说说?

@zhangyuan 很感兴趣怎么做这个

NewRelic 可以实现的

如果想把这些信息存到数据库用来提供查询的话,可以写个 Grape 的 Middleware,其实还是个 rack middleware 可以这样:

class ApiLogger < Grape::Middleware::Base
  def after
    req = request
    request = {
      ip: req.ip,
      method: req.request_method,
      fullpath: req.fullpath,
      headers: req.headers,
      body: env['api.request.input']
    }
    status, headers, bodies = *@app_response

    # record to database

    @app_response
  end
end

然后再 use 这个 middleware 即可

#8 楼 @hemslo 这个方法可以尝试一下!赞!

@hemslo 但是这个方法只会在调用成功后统计,加入调用某个 api 的 validation 失败的话,就不会统计信息了

You need to Sign in before reply, if you don't have an account, please Sign up first.