aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/logger_silence.rb
blob: 125d81d973bb2d4a4dba594c34b49f87a28d574c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'active_support/concern'
require 'active_support/core_ext/module/attribute_accessors'
require 'concurrent'

module LoggerSilence
  extend ActiveSupport::Concern

  included do
    cattr_accessor :silencer
    attr_reader :local_levels
    self.silencer = true
  end

  def after_initialize
    @local_levels = Concurrent::Map.new(:initial_capacity => 2)
  end

  def local_log_id
    Thread.current.__id__
  end

  def level
    local_levels[local_log_id] || super
  end

  # Silences the logger for the duration of the block.
  def silence(temporary_level = Logger::ERROR)
    if silencer
      begin
        old_local_level            = local_levels[local_log_id]
        local_levels[local_log_id] = temporary_level

        yield self
      ensure
        if old_local_level
          local_levels[local_log_id] = old_local_level
        else
          local_levels.delete(local_log_id)
        end
      end
    else
      yield self
    end
  end
end