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.



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

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



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

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



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

def clear_tags!
  current_tags.clear
end

#current_tagsObject



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

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



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

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

#pop_tags(size = 1) ⇒ Object



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

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

#push_tags(*tags) ⇒ Object



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

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



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

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

#tags_textObject



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

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