Class: RedactingLogger

Inherits:
Logger
  • Object
show all
Defined in:
lib/redacting_logger.rb

Overview

RedactingLogger is a custom logger that extends the standard Logger class. It redacts specified patterns in the log messages.

Instance Method Summary collapse

Constructor Details

#initialize(logdev = $stdout, shift_age = 0, shift_size = 1_048_576, redact_patterns: [], redacted_msg: "[REDACTED]", use_default_patterns: true, **kwargs) ⇒ RedactingLogger

Initializes a new instance of the RedactingLogger class.

logdev, shift_age, and shift_size are all using the defaults from the standard Logger class. -> github.com/ruby/logger/blob/0996f90650fd95718f0ffe835b965de18654b71c/lib/logger.rb#L578-L580

Parameters:

  • logdev (Object) (defaults to: $stdout)

    The log device. Defaults to $stdout.

  • shift_age (Integer) (defaults to: 0)

    The number of old log files to keep.

  • shift_size (Integer) (defaults to: 1_048_576)

    The maximum logfile size.

  • redact_patterns (Array<String>) (defaults to: [])

    The patterns to redact from the log messages. Defaults to [].

  • redacted_msg (String) (defaults to: "[REDACTED]")

    The message to replace the redacted patterns with.

  • use_default_patterns (Boolean) (defaults to: true)

    Whether to use the default patterns or not.

  • kwargs (Hash)

    Additional options to pass to the Logger class.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/redacting_logger.rb', line 20

def initialize(
  logdev = $stdout,
  shift_age = 0,
  shift_size = 1_048_576,
  redact_patterns: [],
  redacted_msg: "[REDACTED]",
  use_default_patterns: true,
  **kwargs
)
  super(logdev, shift_age, shift_size, **kwargs)
  @redact_patterns = redact_patterns
  @redacted_msg = redacted_msg
  @redact_patterns += Patterns::DEFAULT if use_default_patterns

  @redact_patterns = Regexp.union(@redact_patterns)
end

Instance Method Details

#add(severity, message = nil, progname = nil) ⇒ Object

Adds a message to the log.

Parameters:

  • severity (Integer)

    The severity level of the message.

  • message (String|Array|Hash) (defaults to: nil)

    The message to log.

  • progname (String) (defaults to: nil)

    The name of the program.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/redacting_logger.rb', line 42

def add(severity, message = nil, progname = nil)
  message, progname = yield if block_given?

  case message

  when String, Symbol, Numeric
    message = message.to_s.gsub(@redact_patterns, @redacted_msg)

  when Array
    message = message.map do |m|
      m.to_s.gsub(@redact_patterns, @redacted_msg)
    end

  when Hash
    message = message.transform_values do |v|
      v.to_s.gsub(@redact_patterns, @redacted_msg)
    end
  end

  progname = progname.to_s.gsub(@redact_patterns, @redacted_msg) if progname

  super
end