Sha256: e17f78545275cce4f3379347c75bc14f1b9f1dc8a83777d9f7449dc33d6bda4d

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

require 'logger'

class BetterLogFormatter < ::Logger::Formatter
  VERSION = "0.1.0".freeze
  Format = "%s%s[%d]%s%s -- %s: %s\n".freeze

  attr_accessor :app_name
  attr_accessor :datetime_display

  def initialize(app_name)
    @app_name = app_name
    @datetime = datetime_display
    super()
  end

  def call(severity, datetime, _, message)
    Format % [formatted_datetime(datetime), app_name, $$, custom_tags, sidekiq_tags, severity_label(severity), msg2str(message)]
  end

  def custom_tag(tag_name, &block)
    @custom_tags ||= {}
    @custom_tags[tag_name] = block
    true
  end

  private

  def custom_tags
    @custom_tags ||= {}
    @custom_tags.map { |_, block| block.call }.compact.map{ |tag| "[#{tag}]" }.join
  end

  def thread_tag
    "TID-#{Thread.current.object_id.to_s(36)}"
  end

  def sidekiq_tags
    return if Thread.current[:sidekiq_context].nil?

    tags = Thread.current[:sidekiq_context].flat_map(&:split) || []
    "[#{thread_tag}]#{tags.map { |tag| "[#{tag}]" }.join}"
  end

  def formatted_datetime(datetime)
    format_datetime(datetime) if datetime_display
  end

  def severity_label(severity)
    severity.is_a?(Fixnum) ? ::Logger::SEV_LABEL[severity] : severity
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
better_log_formatter-0.1.0 lib/better_log_formatter.rb