Skip to content

Commit 70faa78

Browse files
committed
Add TaggedLogging support
Code grabbed from graylog-labs#81 Signed-off-by: Adam Tharani <[email protected]>
1 parent c6831f1 commit 70faa78

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

lib/gelf/logger.rb

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ module GELF
22
# Methods for compatibility with Ruby Logger.
33
module LoggerCompatibility
44

5-
attr_accessor :formatter
5+
attr_accessor :formatter, :log_tags
66

77
# Use it like Logger#add... or better not to use at all.
88
def add(level, message = nil, progname = nil, &block)
@@ -28,9 +28,14 @@ def add(level, message = nil, progname = nil, &block)
2828
message_hash.merge!(self.class.extract_hash_from_exception(message))
2929
end
3030

31-
if message_hash.key?('short_message') && !message_hash['short_message'].empty?
32-
notify_with_level(level, message_hash)
31+
return if !message_hash.key?('short_message') || message_hash['short_message'].empty?
32+
33+
# Include tags in message hash
34+
Array(log_tags).each_with_index do |tag_name, index|
35+
message_hash.merge!("_#{tag_name}" => current_tags[index]) if current_tags[index]
3336
end
37+
38+
notify_with_level(level, message_hash)
3439
end
3540

3641
# Redefines methods in +Notifier+.
@@ -51,12 +56,37 @@ def add(level, message = nil, progname = nil, &block)
5156
def <<(message)
5257
notify_with_level(GELF::UNKNOWN, 'short_message' => message)
5358
end
59+
60+
def tagged(*tags)
61+
new_tags = push_tags(*tags)
62+
yield self
63+
ensure
64+
current_tags.pop(new_tags.size)
65+
end
66+
67+
def push_tags(*tags)
68+
tags.flatten.reject { |t| t.respond_to?(:empty?) ? !!t.empty? : !t }.tap do |new_tags|
69+
current_tags.concat new_tags
70+
end
71+
end
72+
73+
def current_tags
74+
val = Thread.current.thread_variable_get(:gelf_tagged_logging_tags)
75+
return val unless val.nil?
76+
Thread.current.thread_variable_set(:gelf_tagged_logging_tags, [])
77+
end
5478
end
5579

5680
# Graylog2 notifier, compatible with Ruby Logger.
5781
# You can use it with Rails like this:
5882
# config.logger = GELF::Logger.new("localhost", 12201, "WAN", { :facility => "appname" })
5983
# config.colorize_logging = false
84+
#
85+
# Tagged logging (with tags from rack middleware) (order of tags is important)
86+
# Adds custom gelf messages: { '_uuid_name' => <uuid>, '_remote_ip_name' => <remote_ip> }
87+
# config.logger = GELF::Logger.new("localhost", 12201, "LAN", { :facility => "appname" })
88+
# config.log_tags = [:uuid, :remote_ip]
89+
# config.logger.log_tags = [:uuid_name, :remote_ip_name] # Same order as config.log_tags
6090
class Logger < Notifier
6191
include LoggerCompatibility
6292
end

0 commit comments

Comments
 (0)