Sha256: b443fd59e28ec5f967c2f2a07a0e4c277137b10d7972f56a542f80b25fe90c4a

Contents?: true

Size: 1.49 KB

Versions: 6

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

require 'ecs_logging/formatter'

module Loggable
  module EcsLogging
    # A monkey patch to the ::EcsLogging::Formatter to customize how messages from lograge are rendered
    module FormatterMonkeyPatch
      def call(severity, time, progname, msg, **extras)
        base = {
          '@timestamp': time.utc.iso8601(3),
          'log.level': severity,
          message: msg,
          'ecs.version': '1.4.0'
        }

        base['log.logger'] = progname if progname

        base.merge!(msg.except(:lograge)) if msg.is_a?(Hash) && msg.key?(:lograge)
        base.merge!(extras) if extras

        "#{JSON.fast_generate(base)}\n"
      end

      class << self
        def apply_patch
          const = find_const
          mtd = find_method(const)

          # byebug
          const.prepend(self) if const && mtd && mtd.arity == -5
        end

        private

        def find_const
          Kernel.const_get('::EcsLogging::Formatter')
        rescue NameError
          puts '[WARN] ::EcsLogging::Formatter not found. Patch could not be applied.' # rubocop:disable Rails/Output
        end

        def find_method(const)
          return unless const

          method_name = :call
          const.instance_method(method_name)
        rescue NameError
          puts "[WARN] '#{method_name}' method not found in '#{const}'. Patch could not be applied." # rubocop:disable Rails/Output
        end
      end
    end
  end
end

Loggable::EcsLogging::FormatterMonkeyPatch.apply_patch

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
researchable_loggable-1.3.1 lib/loggable/ecs_logging/formatter_monkey_patch.rb
researchable_loggable-1.3.0 lib/loggable/ecs_logging/formatter_monkey_patch.rb
researchable_loggable-1.2.0 lib/loggable/ecs_logging/formatter_monkey_patch.rb
researchable_loggable-1.1.0 lib/loggable/ecs_logging/formatter_monkey_patch.rb
researchable_loggable-1.0.2 lib/loggable/ecs_logging/formatter_monkey_patch.rb
researchable_loggable-1.0.1 lib/loggable/ecs_logging/formatter_monkey_patch.rb