@@ -2,7 +2,7 @@ module GELF
2
2
# Methods for compatibility with Ruby Logger.
3
3
module LoggerCompatibility
4
4
5
- attr_accessor :formatter
5
+ attr_accessor :formatter , :log_tags
6
6
7
7
# Use it like Logger#add... or better not to use at all.
8
8
def add ( level , message = nil , progname = nil , &block )
@@ -28,9 +28,14 @@ def add(level, message = nil, progname = nil, &block)
28
28
message_hash . merge! ( self . class . extract_hash_from_exception ( message ) )
29
29
end
30
30
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 ]
33
36
end
37
+
38
+ notify_with_level ( level , message_hash )
34
39
end
35
40
36
41
# Redefines methods in +Notifier+.
@@ -51,12 +56,37 @@ def add(level, message = nil, progname = nil, &block)
51
56
def <<( message )
52
57
notify_with_level ( GELF ::UNKNOWN , 'short_message' => message )
53
58
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
54
78
end
55
79
56
80
# Graylog2 notifier, compatible with Ruby Logger.
57
81
# You can use it with Rails like this:
58
82
# config.logger = GELF::Logger.new("localhost", 12201, "WAN", { :facility => "appname" })
59
83
# 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
60
90
class Logger < Notifier
61
91
include LoggerCompatibility
62
92
end
0 commit comments