删除Sinatra应用程序中的默认路由日志记录

时间:2012-05-15 07:20:36

标签: ruby logging sinatra

我有一个带有/ health / api端点的Sintra应用程序,如下所述,我的负载均衡器会每秒调用多次。我想删除仅此路由的默认日志记录,或者相反只打印日志,只关注我关心的端点。

get '/health/api' do
  # Health Check
  'I keep quiet'
end

get '/members' do
  # get members data
  'This request gets logged'
end

1 个答案:

答案 0 :(得分:4)

您无法将默认的Rack :: CommonLogger配置为仅打印某些请求,并在其他请求上保持安静。但您可以禁用默认的CommonLogger并使用您自己的过滤功能:

require 'rubygems'
require 'rack'
require 'sinatra'

LOGGING_BLACKLIST = ['/health/api']

class FilteredCommonLogger < Rack::CommonLogger
  def call(env)
    if filter_log(env)
      # default CommonLogger behaviour: log and move on
      super
    else
      # pass request to next component without logging
      @app.call(env)
    end
  end

  # return true if request should be logged
  def filter_log(env)
    !LOGGING_BLACKLIST.include?(env['PATH_INFO'])
  end
end

disable :logging
use FilteredCommonLogger

get '/members' do
  # get members data
  'This request gets logged'
end

get '/health/api' do
  # Health Check
  'I keep quiet'
end

您显然也可以编写仅记录“白名单”请求的自定义记录器。