Skip to content

Instantly share code, notes, and snippets.

@lawrencejones
Created September 6, 2019 10:26
Show Gist options
  • Save lawrencejones/ae93038067985acd2630717bc8e4ae9f to your computer and use it in GitHub Desktop.
Save lawrencejones/ae93038067985acd2630717bc8e4ae9f to your computer and use it in GitHub Desktop.
Simple logfmt logger in Ruby
# frozen_string_literal: true
require "logger"
require "values"
module App
module Logger
class ContextualLogger < Value.new(:logger, :context)
def log(**kwargs)
logger.info(context.merge(kwargs))
end
def with(additional_context)
super(context: context.merge(additional_context))
end
end
@logger = ::Logger.new(STDERR)
@logger.formatter = proc do |_severity, datetime, _progname, payload|
entry = {
ts: datetime.strftime("%Y-%m-%dT%H:%M:%S.%NZ"),
tid: Thread.current.object_id,
}.merge(payload)
entry.reduce("") { |a, (k, v)| a + "#{k}=\"#{v.to_s.gsub('"', '\\"')}\" " } + "\n"
end
def self.with(**context)
ContextualLogger.new(@logger, context)
end
def self.log(**kwargs)
@logger.info(kwargs)
end
def log(**kwargs)
@logger.info(kwargs)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment