Class: SemanticLogger::Formatters::Pattern

Inherits:
Default
  • Object
show all
Defined in:
lib/semantic_logger/formatters/pattern.rb

Overview

Formats log messages using a configurable pattern string, so a custom log line layout can be specified directly in the configuration without having to write a new formatter class.

Pattern placeholders use the form %{directive}, where directive is the name of any of the formatting methods (inherited from Default, or defined below). Named tags support a parameterized form: %{named_tags:request_id} returns the value of a single named tag. Use %%{...} to emit a literal %{...} without interpolation.

Example:

SemanticLogger.add_appender(
io:        $stdout,
formatter: {
  pattern: { pattern: "%{time} %{level} %{name} -- %{message}" }
}
)

Available directives:

time                 Formatted timestamp. Optionally accepts a strftime
                   format, e.g. time:%Y-%m-%dT%H:%M:%S.%6N.
level                Full level name, e.g. "debug".
level_short          Single character level, e.g. "D".
name                 Logger / class name.
message              Log message.
payload              Payload rendered as a string.
exception_class      Class of the logged exception, e.g. "RuntimeError".
exception_message    Message of the logged exception.
exception_details    Detail Ruby adds to the exception's message, such as
                   did_you_mean suggestions (see the log_exception_details option).
backtrace            Backtrace of the logged exception.
duration             Human readable duration, e.g. "1.2ms".
duration_ms          Duration in milliseconds (numeric).
thread_name          Name of the thread that logged the message.
pid                  Process id.
file_name            Ruby file name that logged the message, e.g. "app.rb".
line                 Line number within the Ruby file, e.g. 42.
method               Method that logged the message, e.g. "Order#submit", when
                   the entry has a call site (see SemanticLogger.call_site_level).
tags                 Tags, comma separated.
named_tags           All named tags, or one tag with named_tags:key.
host                 Host name.
application          Application name.
environment          Environment name.

Constant Summary collapse

DEFAULT_PATTERN =

Approximates the Default formatter's output.

"%{time} %{level} [%{pid}:%{thread_name}] %{name} -- %{message}".freeze
DIRECTIVES =

The directives that may appear in a pattern. The value is whether the directive accepts a parameter, e.g. %named_tags:request_id.

{
  time:              true,
  level:             false,
  level_short:       false,
  name:              false,
  message:           false,
  payload:           false,
  exception_class:   false,
  exception_message: false,
  exception_details: false,
  backtrace:         false,
  duration:          false,
  duration_ms:       false,
  thread_name:       false,
  pid:               false,
  file_name:         false,
  line:              false,
  method:            false,
  tags:              false,
  named_tags:        true,
  host:              false,
  application:       false,
  environment:       false
}.freeze

Constants inherited from Base

Base::CONTROL_CHARS, Base::CONTROL_CHAR_ESCAPES, Base::PRECISION, Base::UNICODE_CONTROL_CHARS

Instance Attribute Summary collapse

Attributes inherited from Base

#backtrace_cleaner, #escape_control_chars, #log, #log_application, #log_environment, #log_exception_details, #log_host, #logger, #precision, #time_format

Instance Method Summary collapse

Methods inherited from Default

#exception, #exception_details, #file_name_and_line, #method_name, #name, #process_info, #thread_name

Methods inherited from Base

build_time_format, #pid

Constructor Details

#initialize(pattern: DEFAULT_PATTERN, **args) ⇒ Pattern

Parameters:

pattern: [String]
The pattern string used to format every log entry.
Default: DEFAULT_PATTERN

Plus all the options supported by SemanticLogger::Formatters::Base.



97
98
99
100
101
102
103
104
# File 'lib/semantic_logger/formatters/pattern.rb', line 97

def initialize(pattern: DEFAULT_PATTERN, **args)
  @pattern = pattern
  super(**args)
  # Parse the pattern once, up front, so that formatting every log entry
  # is just a walk over the pre-compiled tokens (no regex on the hot path).
  # Unknown directives raise here, at configuration time, not per log.
  @tokens = compile(compilable(pattern)).map { |token| joinable_token(token) }
end

Instance Attribute Details

#pattern ⇒ Object (readonly)

Returns the value of attribute pattern.



50
51
52
# File 'lib/semantic_logger/formatters/pattern.rb', line 50

def pattern
  @pattern
end

Instance Method Details

#application ⇒ Object

Application name.



203
204
205
# File 'lib/semantic_logger/formatters/pattern.rb', line 203

def application
  joinable_text(logger&.application) if log_application
end

#backtrace ⇒ Object

Backtrace of the logged exception.



146
147
148
# File 'lib/semantic_logger/formatters/pattern.rb', line 146

def backtrace
  exception_backtrace if log.exception
end

#call(log, logger) ⇒ Object



212
213
214
215
216
217
218
219
# File 'lib/semantic_logger/formatters/pattern.rb', line 212

def call(log, logger)
  self.log    = log
  self.logger = logger

  @tokens.each_with_object(+"") do |token, out|
    out << (token.is_a?(Token) ? public_send(token.method_name, *token.arguments).to_s : token)
  end
end

#duration ⇒ Object

Human readable duration (without the Default formatter's surrounding parentheses).



151
152
153
# File 'lib/semantic_logger/formatters/pattern.rb', line 151

def duration
  log.duration_human
end

#duration_ms ⇒ Object

Duration in milliseconds.



156
157
158
# File 'lib/semantic_logger/formatters/pattern.rb', line 156

def duration_ms
  log.duration
end

#environment ⇒ Object

Environment name.



208
209
210
# File 'lib/semantic_logger/formatters/pattern.rb', line 208

def environment
  joinable_text(logger&.environment) if log_environment
end

#exception_class ⇒ Object

Class of the logged exception, e.g. "RuntimeError".



136
137
138
# File 'lib/semantic_logger/formatters/pattern.rb', line 136

def exception_class
  Utils.exception_name(log.exception) if log.exception
end

#exception_message ⇒ Object

Message of the logged exception.



141
142
143
# File 'lib/semantic_logger/formatters/pattern.rb', line 141

def exception_message
  escape_control_characters(Utils.exception_message(log.exception)) if log.exception
end

#file_name ⇒ Object

Name of the Ruby file that logged the message, e.g. "app.rb". Escaped like the other fields, since a log call can supply the backtrace it comes from.



162
163
164
# File 'lib/semantic_logger/formatters/pattern.rb', line 162

def file_name
  escape_control_characters(log.file_name_and_line(true)&.first)
end

#host ⇒ Object

Host name.



198
199
200
# File 'lib/semantic_logger/formatters/pattern.rb', line 198

def host
  joinable_text(logger&.host) if log_host
end

#level ⇒ Object

Full level name, e.g. "debug" (Default formatter uses the short "D").



116
117
118
# File 'lib/semantic_logger/formatters/pattern.rb', line 116

def level
  log.level.to_s
end

#level_short ⇒ Object

Single character level, e.g. "D".



121
122
123
# File 'lib/semantic_logger/formatters/pattern.rb', line 121

def level_short
  log.level_to_s
end

#line ⇒ Object

Line number within the Ruby file that logged the message.



167
168
169
# File 'lib/semantic_logger/formatters/pattern.rb', line 167

def line
  log.file_name_and_line(true)&.last
end

#message ⇒ Object

Log message (without the "-- " prefix the Default formatter adds).



126
127
128
# File 'lib/semantic_logger/formatters/pattern.rb', line 126

def message
  escape_control_characters(log.message)
end

#named_tags(key = nil) ⇒ Object

With a key: the value of a single named tag, e.g. %named_tags:request_id. Without a key: all named tags rendered as "key: value, ...".



180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/semantic_logger/formatters/pattern.rb', line 180

def named_tags(key = nil)
  named = log.named_tags
  return if named.nil? || named.empty?

  if key
    escape_control_characters(named[key.to_sym] || named[key.to_s])
  else
    named.map do |name, value|
      "#{escape_control_characters(name)}: #{escape_control_characters(value)}"
    end.join(", ")
  end
end

#payload ⇒ Object

Raw payload rendered as a string.



131
132
133
# File 'lib/semantic_logger/formatters/pattern.rb', line 131

def payload
  escape_control_characters(log.payload_to_s)
end

#tags ⇒ Object

Tags joined by a comma (without the Default formatter's surrounding brackets).



172
173
174
175
176
# File 'lib/semantic_logger/formatters/pattern.rb', line 172

def tags
  return if log.tags.nil? || log.tags.empty?

  log.tags.map { |tag| escape_control_characters(tag) }.join(", ")
end

#time(format = nil) ⇒ Object

Formatted timestamp. With a strftime format argument, e.g. %SemanticLogger::Formatters::Pattern.time:%Y-%m-%dT%H:%M:%Stime:%Y-%m-%dT%H:%M:%S.%6N, the time is formatted with that string. Without an argument it uses the formatter's configured time_format.



109
110
111
112
113
# File 'lib/semantic_logger/formatters/pattern.rb', line 109

def time(format = nil)
  return super() if format.nil?

  log.time.strftime(format)
end