Class: Makit::Logging::Formatters::TextFormatter

Inherits:
Base
  • Object
show all
Defined in:
lib/makit/logging/formatters/text_formatter.rb

Overview

Text formatter with timestamp and log level

Formats log requests as human-readable text with timestamp, log level, and message. This is the most common format for traditional log files.

Examples:

formatter = TextFormatter.new
formatted = formatter.format(log_request)
# => '[2024-01-15 10:30:45] INFO User logged in'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timestamp_format: "%Y-%m-%d %H:%M:%S", include_context: false) ⇒ TextFormatter

Initialize text formatter

Parameters:

  • timestamp_format (String) (defaults to: "%Y-%m-%d %H:%M:%S")

    strftime format for timestamps

  • include_context (Boolean) (defaults to: false)

    whether to include context in output



27
28
29
30
# File 'lib/makit/logging/formatters/text_formatter.rb', line 27

def initialize(timestamp_format: "%Y-%m-%d %H:%M:%S", include_context: false)
  @timestamp_format = timestamp_format
  @include_context = include_context
end

Instance Attribute Details

#include_contextBoolean (readonly)

Returns whether to include context in output.

Returns:

  • (Boolean)

    whether to include context in output



21
22
23
# File 'lib/makit/logging/formatters/text_formatter.rb', line 21

def include_context
  @include_context
end

#timestamp_formatString (readonly)

Returns timestamp format string.

Returns:

  • (String)

    timestamp format string



19
20
21
# File 'lib/makit/logging/formatters/text_formatter.rb', line 19

def timestamp_format
  @timestamp_format
end

Instance Method Details

#configHash

Get formatter configuration

Returns:

  • (Hash)

    formatter configuration



55
56
57
58
59
60
# File 'lib/makit/logging/formatters/text_formatter.rb', line 55

def config
  super.merge(
    timestamp_format: @timestamp_format,
    include_context: @include_context,
  )
end

#format(log_request) ⇒ String

Format log request as text

Parameters:

  • log_request (LogRequest)

    the log request to format

Returns:

  • (String)

    text formatted log entry



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/makit/logging/formatters/text_formatter.rb', line 36

def format(log_request)
  timestamp = log_request.timestamp.strftime(@timestamp_format)
  level = log_request.level.to_s.upcase
  message = log_request.message

  formatted = "[#{timestamp}] #{level} #{message}"

  # Add context if enabled and present
  if @include_context && !log_request.context.empty?
    context_str = log_request.context.map { |k, v| "#{k}=#{v}" }.join(" ")
    formatted += " #{context_str}"
  end

  formatted
end