Class: Kirei::Logging::Logger

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/kirei/logging/logger.rb

Constant Summary collapse

FILTERED =
"[FILTERED]"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLogger

Returns a new instance of Logger.



46
47
48
49
50
# File 'lib/kirei/logging/logger.rb', line 46

def initialize
  super
  @queue = T.let(Thread::Queue.new, Thread::Queue)
  @thread = T.let(start_logging_thread, Thread)
end

Class Method Details

.call(level:, label:, meta: {}) ⇒ Object



79
80
81
82
83
84
85
86
87
88
# File 'lib/kirei/logging/logger.rb', line 79

def self.call(level:, label:, meta: {})
  return if ENV["NO_LOGS"] == "true"
  return if level.serialize < App.config.log_level.serialize

  # must extract data from current thread before passing this down to the logging thread
  meta["enduser.id"] ||= Thread.current[:enduser_id] # OpenTelemetry::SemanticConventions::Trace::ENDUSER_ID
  meta["service.instance.id"] ||= Thread.current[:request_id] # OpenTelemetry::SemanticConventions::Resource::SERVICE_INSTANCE_ID

  instance.call(level: level, label: label, meta: meta)
end

.flatten_hash_and_mask_sensitive_values(hash, prefix = "") ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/kirei/logging/logger.rb', line 153

def self.flatten_hash_and_mask_sensitive_values(hash, prefix = "")
  result = T.let({}, T::Hash[String, T.untyped])
  Kirei::Helpers.deep_stringify_keys!(hash)
  hash = T.cast(hash, T::Hash[String, T.untyped])

  hash.each do |key, value|
    new_prefix = Kirei::Helpers.blank?(prefix) ? key : "#{prefix}.#{key}"

    case value
    when Hash
      # Some libraries have a custom Hash class that inhert from Hash, but act differently, e.g. OmniAuth::AuthHash.
      # This results in `transform_keys` being available but without any effect.
      value = value.to_h if value.class != Hash
      result.merge!(flatten_hash_and_mask_sensitive_values(value.transform_keys(&:to_s), new_prefix))
    when Array
      value.each_with_index do |element, index|
        if element.is_a?(Hash) || element.is_a?(Array)
          result.merge!(flatten_hash_and_mask_sensitive_values({ index => element }, new_prefix))
        else
          result["#{new_prefix}.#{index}"] = element.is_a?(String) ? mask(key, element) : element
        end
      end
    when String then result[new_prefix] = mask(key, value)
    when Numeric, FalseClass, TrueClass, NilClass then result[new_prefix] = value
    else
      if value.respond_to?(:serialize)
        serialized_value = value.serialize
        if serialized_value.is_a?(Hash)
          result.merge!(
            flatten_hash_and_mask_sensitive_values(serialized_value.transform_keys(&:to_s), new_prefix),
          )
        else
          result[new_prefix] = serialized_value&.to_s
        end
      else
        result[new_prefix] = value&.to_s
      end
    end
  end

  result
end

.instanceObject



53
54
55
# File 'lib/kirei/logging/logger.rb', line 53

def self.instance
  @instance ||= new
end

.loggerObject



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/kirei/logging/logger.rb', line 58

def self.logger
  return @logger unless @logger.nil?

  @logger = T.let(nil, T.nilable(::Logger))
  @logger ||= ::Logger.new($stdout)

  # we want the logline to be parseable to JSON
  @logger.formatter = proc do |_severity, _datetime, _progname, msg|
    "#{msg}\n"
  end

  @logger
end

.mask(k, v) ⇒ Object



142
143
144
# File 'lib/kirei/logging/logger.rb', line 142

def self.mask(k, v)
  App.config.sensitive_keys.any? { k.match?(_1) } ? FILTERED : v
end

Instance Method Details

#call(level:, label:, meta: {}) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/kirei/logging/logger.rb', line 97

def call(level:, label:, meta: {})
  Kirei::App.config..each_pair do |key, value|
    meta[key] ||= value
  end

  meta["service.name"] ||= Kirei::App.config.app_name # OpenTelemetry::SemanticConventions::Resource::SERVICE_NAME
  meta["service.version"] = Kirei::App.version # OpenTelemetry::SemanticConventions::Resource::SERVICE_VERSION
  meta["timestamp"] ||= Time.now.utc.iso8601
  meta["level"] ||= level.to_human
  meta["label"] ||= label

  @queue << meta
end

#start_logging_threadObject



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/kirei/logging/logger.rb', line 112

def start_logging_thread
  Thread.new do
    Kernel.loop do
      log_data = T.let(@queue.pop, T::Hash[Symbol, T.untyped])
      log_transformer = App.config.log_transformer

      loglines = if log_transformer
        log_transformer.call(log_data)
      else
        [Oj.dump(
          Kirei::Logging::Logger.flatten_hash_and_mask_sensitive_values(log_data),
          Kirei::OJ_OPTIONS,
        )]
      end

      loglines.each do |logline|
        logline = "\n#{logline}\n" if Kirei::App.environment == "development"
        Kirei::Logging::Logger.logger.unknown(logline)
      end
    end
  end
end