# 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