|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module IsItReady |
| 4 | + # This class is a Rack::Middleware implementation that will support us in silencing the |
| 5 | + # logging of calls for incoming requests against the endpoint. Otherwise the app would be |
| 6 | + # writing all requests in the Rails logs, causing an overload of information to be reported |
| 7 | + # that's simply not relevant. The usage of this Middleware can be controlled through the Engine's |
| 8 | + # configuration on whether to silence logging or not. |
| 9 | + class LogSilencer |
| 10 | + # Creates a new instance of the Middleware and initializes it using the Rack standard approach |
| 11 | + # for setting up the required values in a Rack::Middleware. |
| 12 | + def initialize(app, opts = {}) |
| 13 | + @silenced = opts.delete(:silenced) |
| 14 | + @app = app |
| 15 | + end |
| 16 | + |
| 17 | + # Executes the Middleware. |
| 18 | + # If the environment contains the special X-SILENCE-LOGGER header to globally silence the request, |
| 19 | + # or the path matches the provided silence configuration, the middleware will silence Rails for the |
| 20 | + # request, otherwise pass the request along. |
| 21 | + def call(env) |
| 22 | + if ::IsItReady.silence_logs && silence_path?(env['PATH_INFO']) |
| 23 | + ::Rails.logger.silence do |
| 24 | + @app.call(env) |
| 25 | + end |
| 26 | + else |
| 27 | + @app.call(env) |
| 28 | + end |
| 29 | + end |
| 30 | + |
| 31 | + private |
| 32 | + |
| 33 | + # Returns true when the given path needs to be silenced. |
| 34 | + # This uses a manual Regex check, since the .match? method might not exist depending on the Ruby |
| 35 | + # version that's being used for this gem. So we perform a manual match and return true if there's |
| 36 | + # a 0 response. |
| 37 | + def silence_path?(path) |
| 38 | + (path =~ /#{@silenced}/).present? |
| 39 | + end |
| 40 | + end |
| 41 | +end |
0 commit comments