Class: Fixings::SilentLogMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/fixings/silent_log_middleware.rb

Overview

Rack middleware to silence the logger for stuff we don’t need. Uses semantic_logger’s Logger#silence to do stuff, so it’s simple. Based on github.com/stve/silencer

Constant Summary collapse

METHODS =
%i[options get head post put delete trace connect patch].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ SilentLogMiddleware

Returns a new instance of SilentLogMiddleware.



9
10
11
12
13
# File 'lib/fixings/silent_log_middleware.rb', line 9

def initialize(app, options = {})
  @app = app
  @silence = wrap(options.delete(:silence))
  @routes = define_routes(@silence, options)
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/fixings/silent_log_middleware.rb', line 15

def call(env)
  if silent_request?(env)
    Rails.logger.silence(:error) do
      @app.call(env)
    end
  else
    @app.call(env)
  end
end

#define_routes(silence_paths, opts) ⇒ Object



25
26
27
28
29
30
# File 'lib/fixings/silent_log_middleware.rb', line 25

def define_routes(silence_paths, opts)
  METHODS.each_with_object({}) do |method, routes|
    routes[method.to_s.upcase] = wrap(opts.delete(method)) + silence_paths
    routes
  end
end

#silent_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/fixings/silent_log_middleware.rb', line 42

def silent_request?(env)
  (@routes[env["REQUEST_METHOD"]] || @silence).any? do |rule|
    case rule
    when String, Integer
      rule.to_s == env["PATH_INFO"]
    when Regexp
      rule =~ env["PATH_INFO"]
    else
      false
    end
  end
end

#wrap(object) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/fixings/silent_log_middleware.rb', line 32

def wrap(object)
  if object.nil?
    []
  elsif object.respond_to?(:to_ary)
    object.to_ary || [object]
  else
    [object]
  end
end