Module: Kitlog

Defined in:
lib/kitlog.rb

Defined Under Namespace

Classes: ContextualLogger

Constant Summary collapse

FORMATTERS =
{
  json: ->(payload) { payload.to_json },
  logfmt: ->(payload) do
    payload.reduce("") { |a, (k, v)| a + "#{k}=#{v.to_json} " }
  end,
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configure(destination: STDERR, format: nil) ⇒ Object

rubocop:disable Metrics/MethodLength



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kitlog.rb', line 26

def self.configure(destination: STDERR, format: nil)
  format ||= destination.isatty ? :logfmt : :json
  formatter = FORMATTERS.fetch(format)

  @logger = Logger.new(destination)
  @logger.formatter = proc do |_severity, datetime, _progname, payload|
    formatter.call(
      payload.merge(
        ts: datetime.strftime("%Y-%m-%dT%H:%M:%S.%NZ"),
        tid: Thread.current.object_id,
      ),
    ) + "\n"
  end
end

.log(**kwargs) ⇒ Object



52
53
54
# File 'lib/kitlog.rb', line 52

def self.log(**kwargs)
  @logger.info(kwargs)
end

.loggerObject



44
45
46
# File 'lib/kitlog.rb', line 44

def self.logger
  @logger
end

.with(**context) ⇒ Object



48
49
50
# File 'lib/kitlog.rb', line 48

def self.with(**context)
  ContextualLogger.new(@logger, context)
end

Instance Method Details

#log(**kwargs) ⇒ Object



56
57
58
# File 'lib/kitlog.rb', line 56

def log(**kwargs)
  @logger.info(kwargs)
end