Class: SemanticLogger::Formatters::Loki

Inherits:
Base
  • Object
show all
Defined in:
lib/semantic_logger/formatters/loki.rb,
lib/semantic_logger/formatters/loki/labels.rb

Defined Under Namespace

Classes: Labels

Constant Summary collapse

OWN_KEYS =

The names of the structured metadata that this formatter writes itself for the fields of an entry, to which the labels named by structured_metadata: are added (see #initialize). A payload key that Loki would store under one of this formatter's own names is written with PAYLOAD_PREFIX, as in payload_duration, whether or not the entry has that field, so that each name always holds this formatter's value. Loki keeps one value of a name: the last of a name written twice, but of names that it stores alike, such as metric.value and metric_value (see .own_name), the one it had to change. So the payload's value would otherwise be lost, or replace this formatter's.

%w[
  metric metric_value dimensions duration duration_human exception_name exception_message
  stack_trace
].freeze
STRUCTURED_METADATA =

The labels that structured_metadata: can write to the structured metadata instead (see #initialize).

%i[pid thread].freeze
LOKI_SEPARATOR =

A run of characters other than ASCII letters and digits, which Loki replaces with one underscore in the name of structured metadata. So Loki stores metric.value, metric__value, and metric followed by a zero width space and value all as metric_value.

/[^A-Za-z0-9]+/
OWN_NAME =

Matches a name that Loki stores as one of OWN_KEYS.

own_name(OWN_KEYS)
LETTER_OR_DIGIT =

Matches a name that holds an ASCII letter or digit. Loki rejects the whole push for a structured metadata name without one, such as an empty name, -, or _, since it would store it as an empty name or as _.

/[A-Za-z0-9]/
PAYLOAD_PREFIX =

The prefix of a payload key named like one of this formatter's own structured metadata names, or without a letter or digit. The :logfmt and :open_telemetry formatters write payload., which Loki would store as payload_.

"payload_".freeze
LEADING_DIGIT =

A name that starts with a digit, which Loki stores with key_ before it.

/\A[0-9]/

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

build_time_format, #pid

Constructor Details

#initialize(structured_metadata: nil, max_label_names_per_series: 15, max_label_name_length: 1024, max_label_value_length: 2048, **args) ⇒ Loki

Parameters structured_metadata: [Array] The labels to write to the structured metadata instead, as Strings: :pid, the process id, :thread, the thread name, both, or neither. Loki advises against labels like these, whose values are many and change: each process, and each of its threads, adds a stream, which Loki indexes and stores apart. As structured metadata, a query can still filter on them, as in {application="shop"} | thread="worker-1". Their names are then among this formatter's own: a payload key of that name is written with PAYLOAD_PREFIX, as a key named like one of its other fields is, and a named tag or context key of that name is written as a label with a number, as in thread_2, since Loki would show the structured metadata as thread_extracted beside a label of its name. Structured metadata needs a Loki that accepts it, with schema v13 and allow_structured_metadata, which is on by default since Loki 3.0. Any other Loki rejects each entry that has structured metadata, which with :pid is every entry. Default: neither, so that both are labels, with a deprecation warning, since Semantic Logger v6 writes both to the structured metadata by default. Supply [] to keep both as labels without it.

max_label_names_per_series: [Integer]
The most labels that Loki accepts for a stream. Loki rejects the whole push, with every
entry in it, for a stream with more, so a label past it, in the order they are written
(see #build_stream), is written to the structured metadata instead.
Default: 15, as Loki's `max_label_names_per_series`
max_label_name_length: [Integer]
The longest label name, in bytes, that Loki accepts. A label with a longer name is
written to the structured metadata instead.
Default: 1024, as Loki's `max_label_name_length`
max_label_value_length: [Integer]
The longest label value, in bytes, that Loki accepts. A label with a longer value, such as
many tags, is written to the structured metadata instead.
Default: 2048, as Loki's `max_label_value_length`

Set each limit, an Integer of 1 or more, to the limit of the same name in the
`limits_config` of a Loki tenant that raises it.

See Formatters::Base for the other options.

The instance variables that are not options are named for Loki, as in @loki_pid_label, so that they are not names that a subclass may already use for its own.



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/semantic_logger/formatters/loki.rb', line 105

def initialize(structured_metadata: nil, max_label_names_per_series: 15, max_label_name_length: 1024,
               max_label_value_length: 2048, **args)
  super(**args)
  @structured_metadata        = ()
  @loki_metadata_labels       = @structured_metadata.map(&:name).freeze
  @loki_own_keys              = (OWN_KEYS + @loki_metadata_labels).freeze
  @loki_own_name              = @loki_metadata_labels.empty? ? OWN_NAME : Loki.own_name(@loki_own_keys)
  @loki_pid_label             = !@structured_metadata.include?(:pid)
  @loki_thread_label          = !@structured_metadata.include?(:thread)
  @max_label_names_per_series = label_limit(:max_label_names_per_series, max_label_names_per_series)
  @max_label_name_length      = label_limit(:max_label_name_length, max_label_name_length)
  @max_label_value_length     = label_limit(:max_label_value_length, max_label_value_length)
end

Instance Attribute Details

#max_label_name_length ⇒ Object (readonly)

The most labels that Loki accepts for a stream, its max_label_names_per_series, the longest label name, its max_label_name_length, and the longest label value, its max_label_value_length, in bytes, unless a Loki tenant's limits_config raises them. See #initialize.



60
61
62
# File 'lib/semantic_logger/formatters/loki.rb', line 60

def max_label_name_length
  @max_label_name_length
end

#max_label_names_per_series ⇒ Object (readonly)

The most labels that Loki accepts for a stream, its max_label_names_per_series, the longest label name, its max_label_name_length, and the longest label value, its max_label_value_length, in bytes, unless a Loki tenant's limits_config raises them. See #initialize.



60
61
62
# File 'lib/semantic_logger/formatters/loki.rb', line 60

def max_label_names_per_series
  @max_label_names_per_series
end

#max_label_value_length ⇒ Object (readonly)

The most labels that Loki accepts for a stream, its max_label_names_per_series, the longest label name, its max_label_name_length, and the longest label value, its max_label_value_length, in bytes, unless a Loki tenant's limits_config raises them. See #initialize.



60
61
62
# File 'lib/semantic_logger/formatters/loki.rb', line 60

def max_label_value_length
  @max_label_value_length
end

#payload_value ⇒ Object

Returns the value of attribute payload_value.



7
8
9
# File 'lib/semantic_logger/formatters/loki.rb', line 7

def payload_value
  @payload_value
end

#stream ⇒ Object

Returns the value of attribute stream.



7
8
9
# File 'lib/semantic_logger/formatters/loki.rb', line 7

def stream
  @stream
end

#structured_metadata ⇒ Object (readonly)

The labels that are written to the structured metadata instead (see #initialize): a frozen Array of :pid, :thread, both, or neither.



64
65
66
# File 'lib/semantic_logger/formatters/loki.rb', line 64

def 
  @structured_metadata
end

Class Method Details

.free_name(names, name, stem = name, reserved: nil) ⇒ Object

Returns [String|nil] the name under which to write a value, among names, a Hash of the names already written and their values: the name itself when it is free; when another value has it, the first name with a number after it that is free, as in request_id_2, so that both values are kept, since Loki keeps one value of a name; or nil when the block returns true for the value of that name, or of a numbered name before it, as the same value, so that it is written once. Both the labels (see Labels) and the structured metadata (see #write_moved_labels) are named so.

The number is added to the stem, which is the name unless given. For structured metadata it is the name without a trailing underscore, so that payload_ is numbered payload_2, as Loki would store payload__2. A name in reserved, which a value outside names has, is never free, nor the same, such as the label thread while the thread is structured metadata (see Labels).



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/semantic_logger/formatters/loki.rb', line 132

def self.free_name(names, name, stem = name, reserved: nil)
  candidate = name
  number    = 1
  while names.key?(candidate) || reserved&.include?(candidate)
    return if names.key?(candidate) && yield(names[candidate])

    number   += 1
    candidate = "#{stem}_#{number}"
  end
  candidate
end

.loki_name(name) ⇒ Object

Returns [String] the name that Loki stores structured metadata of the supplied name under: in UTF-8 without invalid bytes, as Utils.to_json writes it, with each run of characters other than ASCII letters and digits replaced with one underscore, and key_ before a name that starts with a digit.

The key_ cannot change which name a prefixed key gets: that name starts with PAYLOAD_PREFIX, and only the other keys it is checked against can start with a digit. It is there so that this returns the name Loki stores for any name, not only for the names it is used for here.



153
154
155
156
# File 'lib/semantic_logger/formatters/loki.rb', line 153

def self.loki_name(name)
  name = Utils.encode_utf8_string(name).gsub(LOKI_SEPARATOR, "_")
  name.match?(LEADING_DIGIT) ? "key_#{name}" : name
end

.own_name(names) ⇒ Object

Returns [Regexp] a pattern that matches a name that Loki stores as one of the supplied names: each underscore of a name stands for a LOKI_SEPARATOR. Matching it allocates nothing, unlike comparing #loki_name with each name, and nearly every payload key is checked against it.



36
37
38
# File 'lib/semantic_logger/formatters/loki.rb', line 36

def self.own_name(names)
  /\A(?:#{names.map { |name| name.gsub('_', LOKI_SEPARATOR.source) }.join('|')})\z/
end

Instance Method Details

#batch(logs, logger) ⇒ Object

Returns [String] a JSON batch of logs



167
168
169
170
171
172
173
174
175
176
# File 'lib/semantic_logger/formatters/loki.rb', line 167

def batch(logs, logger)
  self.logger = logger

  streams = logs.map do |log|
    self.log = log
    loki_stream
  end

  Utils.to_json({streams: streams})
end

#call(log, logger) ⇒ Object

Returns [String] a single JSON log



159
160
161
162
163
164
# File 'lib/semantic_logger/formatters/loki.rb', line 159

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

  Utils.to_json({streams: [loki_stream]})
end