aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/logger_thread_safe_level.rb
blob: f16c90cfc6150977aac5e185a391d1c8bfaf6e7b (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
46
47
48
49
50
51
52
53
54
55
# frozen_string_literal: true

require "active_support/concern"
require "active_support/core_ext/module/attribute_accessors"
require "concurrent"

module ActiveSupport
  module LoggerThreadSafeLevel # :nodoc:
    extend ActiveSupport::Concern

    included do
      cattr_accessor :local_levels, default: Concurrent::Map.new(initial_capacity: 2), instance_accessor: false
    end

    Logger::Severity.constants.each do |severity|
      class_eval(<<-EOT, __FILE__, __LINE__ + 1)
        def #{severity.downcase}?                # def debug?
          Logger::#{severity} >= level           #   DEBUG >= level
        end                                      # end
      EOT
    end

    def after_initialize
      ActiveSupport::Deprecation.warn(
        "Logger don't need to call #after_initialize directly anymore. It will be deprecated without replacement in " \
        "Rails 6.1."
      )
    end

    def local_log_id
      Thread.current.__id__
    end

    def local_level
      self.class.local_levels[local_log_id]
    end

    def local_level=(level)
      if level
        self.class.local_levels[local_log_id] = level
      else
        self.class.local_levels.delete(local_log_id)
      end
    end

    def level
      local_level || super
    end

    def add(severity, message = nil, progname = nil, &block) # :nodoc:
      return true if @logdev.nil? || (severity || UNKNOWN) < level
      super
    end
  end
end