Module: JsonLogging::JsonLoggerExtension

Included in:
JsonLogger
Defined in:
lib/json_logging/json_logger_extension.rb

Overview

Module that extends any Logger with JSON formatting capabilities This is used by JsonLogging.new to wrap standard loggers

Instance Method Summary collapse

Instance Method Details

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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/json_logging/json_logger_extension.rb', line 20

def add(severity, message = nil, progname = nil, &block)
  return true if severity < level

  msg = nil
  msg = extract_log_message(message, progname, &block)
  line = LineEncoder.build_line(
    msg: msg,
    severity: severity,
    timestamp: Helpers.current_timestamp,
    tags: formatter.current_tags,
    additional_context: JsonLogging.additional_context_for_payload,
    additional_context_sanitized: true,
    sanitize_tags: false
  )
  @logdev&.write(line)
  true
rescue => e
  write_add_fallback(severity, msg, e)
  true
end

#flushObject

Flush tags (used by Rails when request completes)



63
64
65
66
# File 'lib/json_logging/json_logger_extension.rb', line 63

def flush
  clear_tags!
  super if defined?(super)
end

#format_message(severity, datetime, progname, msg) ⇒ Object

Override format_message to ensure it uses JSON formatting even if called directly



42
43
44
# File 'lib/json_logging/json_logger_extension.rb', line 42

def format_message(severity, datetime, progname, msg)
  formatter.call(severity, datetime, progname, msg)
end

#formatterObject



5
6
7
8
9
10
11
# File 'lib/json_logging/json_logger_extension.rb', line 5

def formatter
  @formatter_with_tags ||= begin
    formatter_with_tags = FormatterWithTags.new(self)
    instance_variable_set(:@formatter, formatter_with_tags)
    formatter_with_tags
  end
end

#formatter=(_ignored) ⇒ Object



13
14
15
16
17
18
# File 'lib/json_logging/json_logger_extension.rb', line 13

def formatter=(_ignored)
  # Custom formatters are ignored; JSON output requires FormatterWithTags.
  formatter_with_tags = @formatter_with_tags || FormatterWithTags.new(self)
  instance_variable_set(:@formatter, formatter_with_tags)
  @formatter_with_tags = formatter_with_tags
end

#tagged(*tags) ⇒ Object

Native tag support compatible with Rails.logger.tagged



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/json_logging/json_logger_extension.rb', line 47

def tagged(*tags)
  if block_given?
    formatter.tagged(*tags) { yield self }
  else
    # Return a new wrapped logger with tags applied (similar to TaggedLogging)
    logger = JsonLogging.new(self)
    # Extend formatter with LocalTagStorage to preserve current tags when creating nested loggers
    # This matches Rails' TaggedLogging behavior
    logger.formatter.extend(LocalTagStorage)
    # Push tags through formatter (matches Rails delegation pattern)
    logger.formatter.push_tags(*formatter.current_tags, *tags)
    logger
  end
end