Class: CxLog::Log

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/cx_log/log.rb

Overview

internal class to store the events for a single log entry

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLog

Returns a new instance of Log.



42
43
44
45
# File 'lib/cx_log/log.rb', line 42

def initialize
  @context = default_context
  @options = default_options
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



9
10
11
# File 'lib/cx_log/log.rb', line 9

def context
  @context
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/cx_log/log.rb', line 9

def options
  @options
end

Class Method Details

.add(**kwargs) ⇒ Object



12
13
14
# File 'lib/cx_log/log.rb', line 12

def add(**kwargs)
  instance.add(**kwargs)
end

.clearObject



16
17
18
# File 'lib/cx_log/log.rb', line 16

def clear
  instance.clear
end

.flushObject



20
21
22
# File 'lib/cx_log/log.rb', line 20

def flush
  instance.flush
end

.options=(**options) ⇒ Object



24
25
26
# File 'lib/cx_log/log.rb', line 24

def options=(**options)
  instance.options = options
end

Instance Method Details

#add(**kwargs) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/cx_log/log.rb', line 51

def add(**kwargs)
  kwargs.each do |key, value|
    @context[key] = if @context.key?(key) && key.to_sym != :message
                      [@context[key], value].flatten
                    else
                      value
                    end
  end
  # return instance to allow chaining
  self
end

#clearObject



63
64
65
# File 'lib/cx_log/log.rb', line 63

def clear
  @context = default_context
end

#default_contextObject



29
30
31
32
33
# File 'lib/cx_log/log.rb', line 29

def default_context
  {
    message: ""
  }
end

#default_optionsObject



35
36
37
38
39
40
# File 'lib/cx_log/log.rb', line 35

def default_options
  {
    formatter: CxLog::Formatters::Json.new,
    filter_parameters: i[passw secret token key _key salt cert]
  }
end

#flush(logger) ⇒ Object



67
68
69
70
71
# File 'lib/cx_log/log.rb', line 67

def flush(logger)
  log_level = @context.key?(:error) ? :error : :info
  logger.public_send(log_level, @options[:formatter].call(sanitized_context))
  clear
end

#sanitized_contextObject



73
74
75
76
77
78
79
80
81
# File 'lib/cx_log/log.rb', line 73

def sanitized_context
  @context.to_a.map do |key, value|
    if sensitive_key?(key)
      [key, "[FILTERED]"]
    else
      [key, value]
    end
  end.to_h
end

#sensitive_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
86
# File 'lib/cx_log/log.rb', line 83

def sensitive_key?(key)
  regex = Regexp.union(@options[:filter_parameters].map(&:to_s))
  key.to_s.match?(regex)
end