Sha256: 8b8c9c12a90f7b0090c44873574e5e291435387c9a0948487c6a2dac8c085e85

Contents?: true

Size: 1.07 KB

Versions: 19

Compression:

Stored size: 1.07 KB

Contents

require 'logger'
require_relative '../hash_extensions'
require_relative 'message'

module Twiglet
  class Formatter < ::Logger::Formatter
    Hash.include HashExtensions

    def initialize(service_name,
                   validator:, default_properties: {},
                   now: -> { Time.now.utc })
      @service_name = service_name
      @now = now
      @default_properties = default_properties
      @validator = validator

      super()
    end

    def call(severity, _time, _progname, msg)
      level = severity.downcase
      message = Message.new(msg)
      @validator.validate(message)
      log(level: level, message: message)
    end

    private

    def log(level:, message:)
      base_message = {
        ecs: {
          version: '1.5.0'
        },
        "@timestamp": @now.call.iso8601(3),
        service: {
          name: @service_name
        },
        log: {
          level: level
        }
      }

      base_message
        .deep_merge(@default_properties.to_nested)
        .deep_merge(message.to_nested)
        .to_json
        .concat("\n")
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
twiglet-3.4.9 lib/twiglet/formatter.rb
twiglet-3.4.8 lib/twiglet/formatter.rb
twiglet-3.4.3 lib/twiglet/formatter.rb
twiglet-3.4.2 lib/twiglet/formatter.rb
twiglet-3.4.1 lib/twiglet/formatter.rb
twiglet-3.4.0 lib/twiglet/formatter.rb
twiglet-3.3.7 lib/twiglet/formatter.rb
twiglet-3.3.6 lib/twiglet/formatter.rb
twiglet-3.3.5 lib/twiglet/formatter.rb
twiglet-3.3.4 lib/twiglet/formatter.rb
twiglet-3.3.3 lib/twiglet/formatter.rb
twiglet-3.3.2 lib/twiglet/formatter.rb
twiglet-3.3.0 lib/twiglet/formatter.rb
twiglet-3.2.5 lib/twiglet/formatter.rb
twiglet-3.2.4 lib/twiglet/formatter.rb
twiglet-3.2.2 lib/twiglet/formatter.rb
twiglet-3.2.1 lib/twiglet/formatter.rb
twiglet-3.2.0 lib/twiglet/formatter.rb
twiglet-3.1.3 lib/twiglet/formatter.rb