Class: Kafka::TaggedLogger

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/kafka/tagged_logger.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger_or_stream = nil) ⇒ TaggedLogger

Returns a new instance of TaggedLogger


59
60
61
62
63
64
65
66
67
68
# File 'lib/kafka/tagged_logger.rb', line 59

def initialize(logger_or_stream = nil)
  logger = if %w(info debug warn error).all? { |s| logger_or_stream.respond_to?(s) }
    logger_or_stream
  elsif logger_or_stream
    ::Logger.new(logger_or_stream)
  else
    ::Logger.new(nil)
  end
  super(logger)
end

Class Method Details

.new(logger_or_stream = nil) ⇒ Object


53
54
55
56
57
# File 'lib/kafka/tagged_logger.rb', line 53

def self.new(logger_or_stream = nil)
  # don't keep wrapping the same logger over and over again
  return logger_or_stream if logger_or_stream.is_a?(TaggedLogger)
  super
end

Instance Method Details

#clear_tags!Object


36
37
38
# File 'lib/kafka/tagged_logger.rb', line 36

def clear_tags!
  current_tags.clear
end

#current_tagsObject


40
41
42
43
44
# File 'lib/kafka/tagged_logger.rb', line 40

def current_tags
  # We use our object ID here to avoid conflicting with other instances
  thread_key = @thread_key ||= "kafka_tagged_logging_tags:#{object_id}".freeze
  Thread.current[thread_key] ||= []
end

#flushObject


70
71
72
73
# File 'lib/kafka/tagged_logger.rb', line 70

def flush
  clear_tags!
  super if defined?(super)
end

#pop_tags(size = 1) ⇒ Object


32
33
34
# File 'lib/kafka/tagged_logger.rb', line 32

def pop_tags(size = 1)
  current_tags.pop size
end

#push_tags(*tags) ⇒ Object


26
27
28
29
30
# File 'lib/kafka/tagged_logger.rb', line 26

def push_tags(*tags)
  tags.flatten.reject { |t| t.nil? || t.empty? }.tap do |new_tags|
    current_tags.concat new_tags
  end
end

#tagged(*tags) ⇒ Object


19
20
21
22
23
24
# File 'lib/kafka/tagged_logger.rb', line 19

def tagged(*tags)
  new_tags = push_tags(*tags)
  yield self
ensure
  pop_tags(new_tags.size)
end

#tags_textObject


46
47
48
49
50
51
# File 'lib/kafka/tagged_logger.rb', line 46

def tags_text
  tags = current_tags
  if tags.any?
    tags.collect { |tag| "[#{tag}] " }.join
  end
end