Sha256: 9f9cba186e51c14fa4fe02a5e00520472755ead383397d01b22ba8e6d41d8bb4

Contents?: true

Size: 1.85 KB

Versions: 1

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

require 'fluent-logger'

module UU
  class LoggerFluent
    class Formatter
      def initialize(context, tag)
        @context = context
        @tag = tag
      end

      attr_reader :context

      def call(severity, msg)
        [@tag, {
          log_level: severity,
          **metadata,
          message: msg,
          **@context.context,
        }]
      end

      def metadata
        location = find_location
        {
          filename: File.basename(location.path),
          method: location.label,
          lineno: location.lineno,
        }
      end

      PATHS = %w[
        /log.rb
        /logger.rb
        /loggable.rb
        /forwardable.rb
      ].freeze

      def find_location
        caller_locations.find do |location_|
          location_.path != __FILE__ &&
            PATHS.none? { |path| location_.path.end_with?(path) }
        end
      end
    end

    class Nil
      def post(*); end
    end

    NIL = Nil.new

    @cached_logger = Hash.new do |hash, key|
      hash[key] =
        Fluent::Logger::FluentLogger.new(
          nil,
          nanosecond_precision: true,
          **key,
        )
    end

    class << self
      attr_reader :cached_logger
    end

    def initialize(cxt, host: ENV['FLUENTD_HOST'], port: ENV['FLUENTD_PORT'])
      @logger =
        if host
          self.class.cached_logger[
            { host: host, **(port ? { port: port.to_i } : {}) }
          ]
        else
          NIL
        end
      @formatter = Formatter.new(cxt, 'tag')
    end

    attr_reader :logger
    attr_accessor :formatter

    def format_message(severity, message)
      @formatter.call(severity, message)
    end

    %i[debug info warn error fatal].each do |severity|
      define_method(severity) do |&block|
        @logger.post(*format_message(severity, block.call))
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
uu-0.2.0 lib/uu/logger_fluent.rb