semantic_logger 5.1.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +13 -12
  3. data/Rakefile +15 -4
  4. data/docs/api.md +196 -19
  5. data/docs/appenders.md +579 -68
  6. data/docs/config.md +647 -38
  7. data/docs/index.md +31 -5
  8. data/docs/log.md +56 -17
  9. data/docs/metrics.md +144 -30
  10. data/docs/operations.md +339 -24
  11. data/docs/rails.md +396 -8
  12. data/docs/security.md +222 -27
  13. data/docs/testing.md +28 -3
  14. data/docs/upgrading.md +938 -7
  15. data/lib/semantic_logger/appender/async.rb +42 -11
  16. data/lib/semantic_logger/appender/bugsnag.rb +7 -2
  17. data/lib/semantic_logger/appender/cloudwatch_logs.rb +168 -33
  18. data/lib/semantic_logger/appender/elasticsearch_base.rb +221 -28
  19. data/lib/semantic_logger/appender/elasticsearch_http.rb +23 -6
  20. data/lib/semantic_logger/appender/file.rb +160 -37
  21. data/lib/semantic_logger/appender/graylog.rb +101 -11
  22. data/lib/semantic_logger/appender/honeybadger.rb +7 -1
  23. data/lib/semantic_logger/appender/honeybadger_insights.rb +8 -2
  24. data/lib/semantic_logger/appender/http.rb +308 -46
  25. data/lib/semantic_logger/appender/io.rb +11 -6
  26. data/lib/semantic_logger/appender/kafka.rb +204 -44
  27. data/lib/semantic_logger/appender/loki.rb +55 -9
  28. data/lib/semantic_logger/appender/mongodb.rb +109 -5
  29. data/lib/semantic_logger/appender/new_relic.rb +3 -4
  30. data/lib/semantic_logger/appender/new_relic_logs.rb +35 -15
  31. data/lib/semantic_logger/appender/open_telemetry.rb +37 -35
  32. data/lib/semantic_logger/appender/rabbitmq.rb +246 -17
  33. data/lib/semantic_logger/appender/sentry.rb +3 -4
  34. data/lib/semantic_logger/appender/sentry_ruby.rb +159 -18
  35. data/lib/semantic_logger/appender/splunk.rb +11 -2
  36. data/lib/semantic_logger/appender/splunk_http.rb +92 -1
  37. data/lib/semantic_logger/appender/syslog.rb +149 -32
  38. data/lib/semantic_logger/appender/tcp.rb +73 -98
  39. data/lib/semantic_logger/appender/text_output.rb +65 -0
  40. data/lib/semantic_logger/appender/udp.rb +140 -18
  41. data/lib/semantic_logger/appender/wrapper.rb +10 -7
  42. data/lib/semantic_logger/appender.rb +115 -10
  43. data/lib/semantic_logger/appenders.rb +145 -5
  44. data/lib/semantic_logger/backtrace_cleaning.rb +77 -0
  45. data/lib/semantic_logger/base.rb +115 -81
  46. data/lib/semantic_logger/call_site.rb +235 -0
  47. data/lib/semantic_logger/context.rb +222 -0
  48. data/lib/semantic_logger/core_ext/process.rb +20 -5
  49. data/lib/semantic_logger/core_ext/warning.rb +70 -0
  50. data/lib/semantic_logger/deprecation.rb +139 -0
  51. data/lib/semantic_logger/exception_details.rb +51 -0
  52. data/lib/semantic_logger/formatters/base.rb +186 -20
  53. data/lib/semantic_logger/formatters/color.rb +18 -3
  54. data/lib/semantic_logger/formatters/default.rb +53 -8
  55. data/lib/semantic_logger/formatters/ecs.rb +9 -4
  56. data/lib/semantic_logger/formatters/json.rb +9 -0
  57. data/lib/semantic_logger/formatters/logfmt.rb +155 -21
  58. data/lib/semantic_logger/formatters/loki/labels.rb +282 -0
  59. data/lib/semantic_logger/formatters/loki.rb +430 -38
  60. data/lib/semantic_logger/formatters/new_relic_logs.rb +15 -13
  61. data/lib/semantic_logger/formatters/one_line.rb +101 -3
  62. data/lib/semantic_logger/formatters/open_telemetry.rb +191 -35
  63. data/lib/semantic_logger/formatters/pattern.rb +68 -12
  64. data/lib/semantic_logger/formatters/raw.rb +40 -11
  65. data/lib/semantic_logger/formatters/signalfx.rb +55 -15
  66. data/lib/semantic_logger/formatters/syslog.rb +114 -20
  67. data/lib/semantic_logger/formatters/syslog_cee.rb +38 -19
  68. data/lib/semantic_logger/formatters/syslog_header.rb +49 -0
  69. data/lib/semantic_logger/formatters.rb +1 -0
  70. data/lib/semantic_logger/levels.rb +10 -1
  71. data/lib/semantic_logger/log.rb +384 -82
  72. data/lib/semantic_logger/loggable.rb +56 -73
  73. data/lib/semantic_logger/logger.rb +31 -5
  74. data/lib/semantic_logger/metric/new_relic.rb +33 -18
  75. data/lib/semantic_logger/metric/signalfx.rb +29 -18
  76. data/lib/semantic_logger/metric/statsd.rb +41 -15
  77. data/lib/semantic_logger/processor.rb +194 -5
  78. data/lib/semantic_logger/queue_processor/backoff.rb +140 -0
  79. data/lib/semantic_logger/queue_processor/batch_failure.rb +69 -0
  80. data/lib/semantic_logger/queue_processor/held_write.rb +62 -0
  81. data/lib/semantic_logger/queue_processor/inbox.rb +97 -0
  82. data/lib/semantic_logger/queue_processor/reopener.rb +56 -0
  83. data/lib/semantic_logger/queue_processor/reporter.rb +113 -0
  84. data/lib/semantic_logger/queue_processor/request.rb +93 -0
  85. data/lib/semantic_logger/queue_processor/throttled_counter.rb +89 -0
  86. data/lib/semantic_logger/queue_processor.rb +519 -170
  87. data/lib/semantic_logger/ractor_copy.rb +120 -0
  88. data/lib/semantic_logger/ractor_processor.rb +82 -0
  89. data/lib/semantic_logger/ractor_receiver.rb +282 -0
  90. data/lib/semantic_logger/ractor_support.rb +28 -0
  91. data/lib/semantic_logger/redactor.rb +310 -0
  92. data/lib/semantic_logger/semantic_logger.rb +328 -81
  93. data/lib/semantic_logger/subscriber.rb +250 -10
  94. data/lib/semantic_logger/sync_processor.rb +237 -26
  95. data/lib/semantic_logger/test/capture_log_events.rb +26 -5
  96. data/lib/semantic_logger/test/minitest.rb +2 -1
  97. data/lib/semantic_logger/test/rspec.rb +1 -1
  98. data/lib/semantic_logger/trap_safe.rb +113 -0
  99. data/lib/semantic_logger/utils.rb +482 -67
  100. data/lib/semantic_logger/version.rb +1 -1
  101. data/lib/semantic_logger.rb +36 -3
  102. metadata +41 -5
  103. data/lib/semantic_logger/core_ext/thread.rb +0 -30
@@ -12,6 +12,18 @@ end
12
12
  module SemanticLogger
13
13
  module Appender
14
14
  class SentryRuby < SemanticLogger::Subscriber
15
+ # Keys of the named tags or payload that set the Sentry user, mapped to its fields.
16
+ USER_KEYS = {user_id: :id, username: :username, user_email: :email, ip_address: :ip_address}.freeze
17
+
18
+ # The types of value taken from the payload for a field of the Sentry user.
19
+ USER_VALUE_TYPES = [String, Symbol, Integer].freeze
20
+
21
+ # The types of value accepted in a fingerprint, which Sentry turns into Strings.
22
+ FINGERPRINT_PART_TYPES = [String, Symbol, Numeric].freeze
23
+
24
+ # The key of the Sentry scope of the thread that logged the entry, as captured with the entry.
25
+ SCOPE_CAPTURE_KEY = :sentry_scope
26
+
15
27
  # Create Appender
16
28
  #
17
29
  # Parameters
@@ -47,6 +59,14 @@ module SemanticLogger
47
59
  end
48
60
  end
49
61
  super
62
+ # Sentry keeps the user, tags, contexts, breadcrumbs, and trace of a request in the Sentry
63
+ # scope of the thread or fiber handling it, but #log runs on the appender thread.
64
+ SemanticLogger::Logger.subscribe(method(:capture_scope))
65
+ end
66
+
67
+ # Stops capturing the Sentry scope of each log entry.
68
+ def close
69
+ SemanticLogger::Logger.unsubscribe(method(:capture_scope))
50
70
  end
51
71
 
52
72
  # Send an error notification to sentry
@@ -54,18 +74,26 @@ module SemanticLogger
54
74
  # Ignore logs coming from Sentry itself
55
75
  return false if log.name == "Sentry"
56
76
 
57
- context = formatter.call(log, self)
58
- payload = context.delete(:payload) || {}
59
- named_tags = context[:named_tags] || {}
60
- transaction_name = named_tags.delete(:transaction_name)
77
+ # Sentry serializes the event with JSON.generate itself, which raises for a binary String
78
+ # that holds bytes outside ASCII (json 3.1), or warns about it (json 2.8 to 3.0.x), and for
79
+ # invalid UTF-8, and then loses the event. So the data is sent as a copy with its text
80
+ # converted to valid UTF-8, as the JSON formatters write it, and a Hash or Array nested too
81
+ # deeply, or that holds itself, cut off there as they cut it off (see Utils.encode_utf8).
82
+ # Any other object is sent as it is, for Sentry to write as it writes it.
83
+ context = format_log(log) { |data| Utils.encode_utf8(data) }
84
+ # The payload and named tags are this appender's own copies (above), so the keys taken out
85
+ # below are left out only of what is sent to Sentry.
86
+ payload = payload_extras(context.delete(:payload), log.payload)
87
+ named_tags = (context[:named_tags] = like_original(context[:named_tags] || {}, log.named_tags))
88
+ transaction_name = named_tags.delete(:transaction_name)
89
+ fingerprint = extract_fingerprint!(named_tags) || extract_fingerprint!(payload, from_payload: true)
61
90
 
62
91
  user = extract_user!(named_tags, payload)
63
92
  tags = extract_tags!(context)
64
93
 
65
- fingerprint = payload.delete(:fingerprint)
66
-
67
94
  ::Sentry.with_scope do |scope|
68
- scope.set_user(user) if user
95
+ apply_captured_scope(scope, log)
96
+ scope.set_user(merged_user(scope.user, user)) if user
69
97
  scope.set_level(context.delete(:level)) if context[:level]
70
98
  scope.set_fingerprint(fingerprint) if fingerprint
71
99
  scope.set_transaction_name(transaction_name) if transaction_name
@@ -87,6 +115,44 @@ module SemanticLogger
87
115
 
88
116
  private
89
117
 
118
+ # As an on_log subscriber, on the thread that logs the entry, keeps a copy of its Sentry scope
119
+ # with the entry when it meets this appender's level. The filter is left to #log, so that it
120
+ # runs once, on the appender thread.
121
+ #
122
+ # The copy leaves out the Rack env: Sentry reads and rewinds the request body in it as it builds
123
+ # the request of an event, which must not happen on the appender thread while the request is
124
+ # still using it, or after it has closed the body.
125
+ def capture_scope(log)
126
+ return if log.captured(SCOPE_CAPTURE_KEY) || log.name == "Sentry"
127
+ return unless ::Sentry.initialized? && meets_log_level?(log)
128
+
129
+ scope = ::Sentry.get_current_scope&.dup
130
+ return unless scope
131
+
132
+ scope.set_rack_env(nil)
133
+ log.capture(SCOPE_CAPTURE_KEY, scope)
134
+ end
135
+
136
+ # Starts the scope of the event from the Sentry scope captured when the entry was logged, so
137
+ # that the event has the user, tags, contexts, breadcrumbs, trace, and event processors of the
138
+ # thread that logged it. Copies it again, since the scope adds tags and extras to its Hashes,
139
+ # which would otherwise be the ones held by the log entry.
140
+ def apply_captured_scope(scope, log)
141
+ captured = log.captured(SCOPE_CAPTURE_KEY)
142
+ return unless captured.is_a?(::Sentry::Scope)
143
+
144
+ captured = captured.dup
145
+ scope.update_from_scope(captured)
146
+ captured.event_processors.each { |processor| scope.add_event_processor(&processor) }
147
+ end
148
+
149
+ # Returns [Hash] the Sentry user of the thread with the fields of the user taken from the
150
+ # named tags, whose keys are Symbols, in place of the same fields, whether keyed by a String or
151
+ # a Symbol.
152
+ def merged_user(thread_user, user)
153
+ thread_user.transform_keys { |key| key.respond_to?(:to_sym) ? key.to_sym : key }.merge(user)
154
+ end
155
+
90
156
  # Use Raw Formatter by default
91
157
  def default_formatter
92
158
  SemanticLogger::Formatters::Raw.new
@@ -100,26 +166,101 @@ module SemanticLogger
100
166
  # Any additional value nested in a :user key will be added, provided any of
101
167
  # the above keys is already present.
102
168
  #
103
- def extract_user!(*sources)
104
- keys = {user_id: :id, username: :username, user_email: :email, ip_address: :ip_address}
105
-
169
+ # The payload can hold untrusted data, such as a request body, so taking the user from it is
170
+ # deprecated, and the named tags win: a payload field is only taken when the named tags do not
171
+ # set it, and its value is a String, Symbol, or Integer. A payload value that is not taken is
172
+ # left where it is, and sent to Sentry as data.
173
+ def extract_user!(named_tags, payload)
106
174
  user = {}
107
175
 
108
- sources.each do |source|
109
- keys.each do |source_key, target_key|
110
- value = source.delete(source_key)
111
- user[target_key] = value if value
176
+ USER_KEYS.each do |source_key, target_key|
177
+ value = named_tags.delete(source_key)
178
+ if value
179
+ user[target_key] = value
180
+ elsif user_value?(payload[source_key])
181
+ user[target_key] = payload.delete(source_key)
182
+ payload_context_deprecated
112
183
  end
113
184
  end
114
185
 
115
186
  return if user.empty?
116
187
 
117
- sources.each do |source|
118
- extras = source.delete(:user)
119
- user.merge!(extras) if extras.is_a?(Hash)
188
+ user.merge!(named_tags.delete(:user)) if named_tags[:user].is_a?(Hash)
189
+ merge_payload_user!(user, payload)
190
+ user
191
+ end
192
+
193
+ # Adds the fields of a :user Hash in the payload that the user does not have yet, when each of
194
+ # its keys is a Symbol or String, and each of its values a String, Symbol, or Integer.
195
+ def merge_payload_user!(user, payload)
196
+ extras = payload[:user]
197
+ return unless extras.is_a?(Hash) && extras.all? { |key, value| user_key?(key) && user_value?(value) }
198
+
199
+ payload.delete(:user)
200
+ payload_context_deprecated
201
+ extras.each do |key, value|
202
+ user[key.to_sym] = value unless user.key?(key.to_sym) || user.key?(key.to_s)
120
203
  end
204
+ end
121
205
 
122
- user
206
+ def user_key?(key)
207
+ key.is_a?(Symbol) || key.is_a?(String)
208
+ end
209
+
210
+ def user_value?(value)
211
+ USER_VALUE_TYPES.any? { |type| value.is_a?(type) }
212
+ end
213
+
214
+ # Returns [Array<String>] the fingerprint taken from the named tags or payload, an Array of
215
+ # Strings, Symbols, or numbers. Returns nil when there is none, or it is of another type, which
216
+ # is then left where it is and sent to Sentry as data. As for the user, taking it from the
217
+ # payload is deprecated.
218
+ def extract_fingerprint!(source, from_payload: false)
219
+ fingerprint = source[:fingerprint]
220
+ return unless fingerprint.is_a?(Array) && fingerprint.all? { |part| fingerprint_part?(part) }
221
+
222
+ payload_context_deprecated if from_payload
223
+ source.delete(:fingerprint).map(&:to_s)
224
+ end
225
+
226
+ def fingerprint_part?(part)
227
+ FINGERPRINT_PART_TYPES.any? { |type| part.is_a?(type) }
228
+ end
229
+
230
+ # Returns [Hash] the payload, from this appender's own copy, as a Hash that keys can be taken out
231
+ # of. A payload that is not a Hash is sent to Sentry as the extra named payload.
232
+ def payload_extras(payload, original)
233
+ case payload
234
+ when nil then {}
235
+ when Hash then like_original(payload, original)
236
+ else {payload: payload}
237
+ end
238
+ end
239
+
240
+ # Returns [Hash] this appender's copy of the payload or named tags as a Hash of the class of the
241
+ # log entry's own, such as HashWithIndifferentAccess, so that the keys taken out of it, such as
242
+ # :user_id, are found as in the application's Hash. The class's own #update may convert the
243
+ # nested Hashes too, as HashWithIndifferentAccess does. A plain Hash, or one whose class cannot
244
+ # be rebuilt this way, is returned as it is.
245
+ def like_original(copy, original)
246
+ return copy if original.instance_of?(Hash) || !original.is_a?(Hash)
247
+
248
+ rebuilt = original.class.new.update(copy)
249
+ rebuilt.is_a?(Hash) ? rebuilt : copy
250
+ rescue StandardError
251
+ copy
252
+ end
253
+
254
+ # Warns once that the Sentry user or fingerprint was taken from the payload.
255
+ def payload_context_deprecated
256
+ return if @payload_context_deprecated
257
+
258
+ @payload_context_deprecated = true
259
+ Deprecation.warn(
260
+ "SemanticLogger::Appender::SentryRuby took the Sentry user or fingerprint from the log payload. " \
261
+ "This is deprecated and will be removed in v6, since the payload can hold untrusted data: " \
262
+ "set them with named tags instead, for example SemanticLogger.tagged(user_id: user.id)."
263
+ )
123
264
  end
124
265
 
125
266
  # Extract tags.
@@ -9,6 +9,10 @@ end
9
9
  #
10
10
  # Use the official splunk gem to log messages to Splunk.
11
11
  #
12
+ # Deprecated: will be removed in v6. Use the :splunk_http appender instead.
13
+ # The splunk-sdk-ruby gem (last released in 2015) does not verify the server's TLS certificate,
14
+ # so its connection, including the login credentials, is open to interception.
15
+ #
12
16
  # Example
13
17
  # SemanticLogger.add_appender(
14
18
  # appender: :splunk,
@@ -77,7 +81,8 @@ module SemanticLogger
77
81
  #
78
82
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
79
83
  # Override the log level for this appender.
80
- # Default: SemanticLogger.default_level
84
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
85
+ # filters by its own level.
81
86
  #
82
87
  # formatter: [Object|Proc]
83
88
  # An instance of a class that implements #call, or a Proc to be used to format
@@ -90,6 +95,10 @@ module SemanticLogger
90
95
  # Proc: Only include log messages where the supplied Proc returns true
91
96
  # The Proc must return true or false.
92
97
  def initialize(index: "main", source_type: nil, **args, &)
98
+ Deprecation.warn(
99
+ "SemanticLogger::Appender::Splunk (appender: :splunk) is deprecated and will be removed in v6. " \
100
+ "Its splunk-sdk-ruby gem does not verify TLS certificates. Use appender: :splunk_http instead."
101
+ )
93
102
  @index = index
94
103
  @source_type = source_type
95
104
 
@@ -109,7 +118,7 @@ module SemanticLogger
109
118
 
110
119
  # Log the message to Splunk
111
120
  def log(log)
112
- event = formatter.call(log, self)
121
+ event = format_log(log)
113
122
  service_index.submit(event.delete(:message), event)
114
123
  true
115
124
  end
@@ -12,9 +12,38 @@ require "json"
12
12
  # url: 'http://localhost:8080',
13
13
  # token: '70CA900C-3D7E-42A4-9C79-7975D1C422A8'
14
14
  # )
15
+ #
16
+ # Batching:
17
+ # Add it with `batch: true` to send many entries in each request, as event objects stacked one after
18
+ # the other, each one what the appender sends for that entry on its own (see #batch).
19
+ #
20
+ # Responses:
21
+ # The HTTP Event Collector answers 400 Bad Request both for the entries a request holds, and for its
22
+ # own configuration, such as an index it does not know. Its JSON body says which, with a numeric
23
+ # `code` and a `text`. A batch it rejects for its configuration is discarded at once, rather than
24
+ # split up to find the entries at fault, since every part would be rejected too (see
25
+ # #fails_any_batch?). For a batch it rejects at one of its events, it says which one, having indexed
26
+ # those before it (see #rejected_entry).
15
27
  module SemanticLogger
16
28
  module Appender
17
29
  class SplunkHttp < SemanticLogger::Appender::Http
30
+ # The status codes in the body of a 400 Bad Request from the HTTP Event Collector that reject
31
+ # the request for the collector's configuration or the appender's, whatever entries it holds:
32
+ # 7 Incorrect index
33
+ # 10 Data channel is missing
34
+ # 11 Invalid data channel
35
+ # 14 ACK is disabled
36
+ # 16 Query string authorization is not enabled
37
+ # 21 Invalid token
38
+ # 22 Token disabled
39
+ # The others it answers with a 400 are caused by the entries, so a batch is split up to find
40
+ # them: 5 No data, 6 Invalid data format, 12 Event field is required, 13 Event field cannot be
41
+ # blank, and 15 Error in handling indexed fields.
42
+ #
43
+ # See "Troubleshoot HTTP Event Collector", Possible error codes:
44
+ # https://help.splunk.com/en/splunk-enterprise/get-started/get-data-in/10.4/get-data-with-http-event-collector/troubleshoot-http-event-collector
45
+ CONFIGURATION_CODES = [7, 10, 11, 14, 16, 21, 22].freeze
46
+
18
47
  attr_accessor :source_type, :index
19
48
 
20
49
  # Create Splunk appender over persistent HTTP(S)
@@ -56,7 +85,8 @@ module SemanticLogger
56
85
  #
57
86
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
58
87
  # Override the log level for this appender.
59
- # Default: SemanticLogger.default_level
88
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
89
+ # filters by its own level.
60
90
  #
61
91
  # formatter: [Object|Proc]
62
92
  # An instance of a class that implements #call, or a Proc to be used to format
@@ -100,6 +130,67 @@ module SemanticLogger
100
130
  message[:index] = index if index
101
131
  Utils.to_json(message)
102
132
  end
133
+
134
+ # Whether the exception would fail any batch, whatever entries it holds (see
135
+ # Http#fails_any_batch?), including a 400 Bad Request whose body holds one of the collector's
136
+ # CONFIGURATION_CODES, such as for a wrong `index:`. So the batch is discarded at once, and
137
+ # reported once, with the collector's text, rather than split up and each entry sent on its own.
138
+ def fails_any_batch?(exception)
139
+ super || (exception.is_a?(ResponseError) && exception.rejected? &&
140
+ CONFIGURATION_CODES.include?(collector_response(exception.body)["code"]))
141
+ end
142
+
143
+ # Send a batch of log messages to the HTTP Event Collector in a single request, as event objects
144
+ # stacked one after the other, the batch format of "Format events for HTTP Event Collector":
145
+ # https://help.splunk.com/en/splunk-enterprise/get-started/get-data-in/10.6/get-data-with-http-event-collector/format-events-for-http-event-collector
146
+ #
147
+ # Each event is what #log sends for that entry, formatted by #format_log. The formatter must
148
+ # format each entry as exactly one event object, as the default one, the appender itself (see
149
+ # #call), does, since the collector names a rejected event by its position in the request (see
150
+ # #rejected_entry).
151
+ # Every entry is formatted before the request is sent, so a format error sends nothing, and the
152
+ # batch is split up to find the entry at fault (see Http#batch_all_or_nothing?).
153
+ def batch(logs)
154
+ message = logs.map { |log| format_log(log) }.join
155
+ logger.trace(message)
156
+ post(message)
157
+ end
158
+
159
+ # Returns [Integer|nil] the position in the batch of the event that the HTTP Event Collector
160
+ # rejected, from the `invalid-event-number` in the body of its 400 Bad Request, such as
161
+ # {"text":"Invalid data format","code":6,"invalid-event-number":2}, or nil when it holds none
162
+ # (see Subscriber#rejected_entry).
163
+ #
164
+ # The collector reads the events of a batch in order, and indexes those before the one it
165
+ # rejects. Splunk's documentation does not say so: "Troubleshoot HTTP Event Collector" and
166
+ # "Format events for HTTP Event Collector" describe neither `invalid-event-number` nor what
167
+ # happens to the rest of a batch. Users report it, for example
168
+ # https://github.com/moby/moby/issues/35862, where a batch of 10 whose last event is malformed,
169
+ # sent again and again, had "the first 1-9 ... accepted by Splunk over and over again".
170
+ #
171
+ # So splitting such a batch to find the event at fault would index the events before it twice.
172
+ # Instead the events before it are counted as written, it is discarded, and those after it,
173
+ # which the collector never read, are sent again. A 400 without the number, such as a proxy's,
174
+ # is split as for Http, and so is any other status, which the collector does not answer with an
175
+ # event number. The number counts events, so a formatter must format each entry as one event
176
+ # object, as the default one does.
177
+ def rejected_entry(exception)
178
+ return unless exception.is_a?(ResponseError) && exception.code == 400
179
+
180
+ collector_response(exception.body)["invalid-event-number"]
181
+ end
182
+
183
+ private
184
+
185
+ # Returns [Hash] the body of a response from the HTTP Event Collector, such as
186
+ # {"text":"Incorrect index","code":7}, or an empty Hash for a body that is not a JSON object,
187
+ # such as a response from a proxy in front of it.
188
+ def collector_response(body)
189
+ parsed = JSON.parse(body.to_s)
190
+ parsed.is_a?(Hash) ? parsed : {}
191
+ rescue JSON::ParserError
192
+ {}
193
+ end
103
194
  end
104
195
  end
105
196
  end
@@ -1,4 +1,3 @@
1
- require "syslog"
2
1
  require "uri"
3
2
  require "socket"
4
3
  # Send log messages to local syslog, or remote syslog servers over TCP or UDP.
@@ -61,7 +60,8 @@ module SemanticLogger
61
60
  #
62
61
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
63
62
  # Override the log level for this appender.
64
- # Default: SemanticLogger.default_level
63
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
64
+ # filters by its own level.
65
65
  #
66
66
  # filter: [Regexp|Proc]
67
67
  # RegExp: Only include log messages where the class name matches the supplied.
@@ -78,7 +78,7 @@ module SemanticLogger
78
78
  # Default: 1024 bytes
79
79
  #
80
80
  # options: [Integer]
81
- # Default: ::Syslog::LOG_PID | ::Syslog::LOG_CONS
81
+ # Default: ::Syslog::LOG_PID | ::Syslog::LOG_CONS (when logging to a local syslog daemon)
82
82
  # Any of the following (options can be logically OR'd together)
83
83
  # ::Syslog::LOG_CONS
84
84
  # ::Syslog::LOG_NDELAY
@@ -91,7 +91,7 @@ module SemanticLogger
91
91
  # I.e. When `url: 'syslog://localhost'`
92
92
  #
93
93
  # facility: [Integer]
94
- # Default: ::Syslog::LOG_USER
94
+ # Default: ::Syslog::LOG_USER (the same value as SemanticLogger::Formatters::Syslog::LOG_USER)
95
95
  # Type of program (can be logically OR'd together)
96
96
  # ::Syslog::LOG_AUTH
97
97
  # ::Syslog::LOG_AUTHPRIV
@@ -124,19 +124,19 @@ module SemanticLogger
124
124
  # # Change the warn level to LOG_NOTICE level instead of a the default of LOG_WARNING.
125
125
  # SemanticLogger.add_appender(appender: :syslog, level_map: {warn: ::Syslog::LOG_NOTICE})
126
126
  def initialize(url: "syslog://localhost",
127
- facility: ::Syslog::LOG_USER,
128
- max_size: 1024,
127
+ facility: SemanticLogger::Formatters::Syslog::LOG_USER,
128
+ max_size: SemanticLogger::Formatters::Syslog::DEFAULT_MAX_SIZE,
129
129
  level_map: SemanticLogger::Formatters::Syslog::LevelMap.new,
130
- options: ::Syslog::LOG_PID | ::Syslog::LOG_CONS,
130
+ options: nil,
131
131
  tcp_client: {},
132
132
  **args,
133
133
  &)
134
134
  @options = options
135
135
  @facility = facility
136
136
  @max_size = max_size
137
- @level_map = level_map
137
+ @level_map = SemanticLogger::Formatters::Syslog::LevelMap.build(level_map)
138
138
  @url = url
139
- uri = URI(@url)
139
+ uri = Utils.parse_url(@url)
140
140
  @server = uri.host || "localhost"
141
141
  @protocol = (uri.scheme || :syslog).to_sym
142
142
  @port = uri.port || 514
@@ -145,62 +145,110 @@ module SemanticLogger
145
145
 
146
146
  raise "Unknown protocol #{@protocol}!" unless %i[syslog tcp udp].include?(@protocol)
147
147
 
148
- # The syslog_protocol gem is required when logging over TCP or UDP.
149
- if %i[tcp udp].include?(@protocol)
148
+ # The syslog gem, a bundled gem since Ruby 3.4, is only required when logging to a local syslog daemon.
149
+ if @protocol == :syslog
150
150
  begin
151
- require "syslog_protocol"
151
+ require "syslog"
152
152
  rescue LoadError
153
153
  raise LoadError,
154
- "Missing gem: syslog_protocol. This gem is required when logging over TCP or UDP. " \
155
- "To fix this error: gem install syslog_protocol"
154
+ "Missing gem: syslog. This gem is required when logging to a local syslog daemon on Ruby 3.4 " \
155
+ 'and later. Please add the gem "syslog" to your Gemfile.'
156
156
  end
157
+ @options ||= ::Syslog::LOG_PID | ::Syslog::LOG_CONS
158
+ end
157
159
 
158
- # The net_tcp_client gem is required when logging over TCP.
159
- if protocol == :tcp
160
- begin
161
- require "net/tcp_client"
162
- rescue LoadError
163
- raise LoadError,
164
- "Missing gem: net_tcp_client. This gem is required when logging over TCP. " \
165
- "To fix this error: gem install net_tcp_client"
166
- end
160
+ # The net_tcp_client gem is required when logging over TCP.
161
+ # The syslog formatters load the syslog_protocol gem that they use to build remote syslog packets.
162
+ if @protocol == :tcp
163
+ begin
164
+ require "net/tcp_client"
165
+ rescue LoadError
166
+ raise LoadError,
167
+ "Missing gem: net_tcp_client. This gem is required when logging over TCP. " \
168
+ "To fix this error: gem install net_tcp_client"
167
169
  end
168
170
  end
169
171
 
172
+ if %i[tcp udp].include?(@protocol)
173
+ # Reject an invalid facility when the appender is created, even with a formatter that ignores it.
174
+ SemanticLogger::Formatters::Syslog.facility_number(@facility)
175
+ end
176
+
170
177
  super(**args, &)
171
178
  reopen
172
179
  end
173
180
 
181
+ # Set the formatter from Symbol|Hash|Block, as for any appender.
182
+ #
183
+ # When sending over TCP or UDP, a formatter named as one of the PACKET_FORMATTERS also gets
184
+ # this appender's facility, level map, and maximum packet size, whether it is supplied when
185
+ # the appender is created or set later.
186
+ def formatter=(formatter)
187
+ super(%i[tcp udp].include?(@protocol) ? with_packet_options(formatter) : formatter)
188
+ end
189
+
174
190
  # After forking an active process call #reopen to re-open
175
191
  # open the handles to resources
192
+ #
193
+ # Over TCP, it connects again, and then closes the connection it replaces, such as after a log rotation.
194
+ # When connecting fails, it raises, and keeps the connection it has. Over UDP, it closes the socket it
195
+ # replaces, which in a forked child is only the child's copy.
196
+ #
197
+ # Over TCP, a child process first forgets the client it inherited, without closing its connection, which
198
+ # belongs to the parent. The child closes only its own copy of the socket's file descriptor, which sends
199
+ # the server nothing, so that the server sees the connection end once the parent closes it, rather than
200
+ # once the child exits, or collects the client. When connecting fails in the child, such as while the
201
+ # server cannot be reached, the appender connects again on its next write, rather than writing through
202
+ # the parent's connection. Over TLS, both processes would then carry on the same TLS session, so that the
203
+ # server could not decrypt what the parent writes next.
176
204
  def reopen
177
205
  case @protocol
178
206
  when :syslog
179
207
  method = ::Syslog.opened? ? :reopen : :open
180
208
  ::Syslog.send(method, application, options, facility)
181
209
  when :tcp
182
- @tcp_client_options[:server] = "#{@server}:#{@port}"
183
- @remote_syslog = Net::TCPClient.new(**@tcp_client_options)
184
- # Use the local logger for @remote_syslog so errors with the remote logger can be recorded locally.
185
- @remote_syslog.logger = logger
210
+ forget_inherited
211
+ replaced = @remote_syslog
212
+ connect_tcp
213
+ close_remote_syslog(replaced, replaced: true)
186
214
  when :udp
215
+ replaced = @remote_syslog
187
216
  @remote_syslog = UDPSocket.new
217
+ close_remote_syslog(replaced, replaced: true)
188
218
  else
189
219
  raise "Unsupported protocol: #{@protocol}"
190
220
  end
191
221
  end
192
222
 
193
- # Write the log using the specified protocol and server.
223
+ # Closes the connection to a remote syslog server, such as when the appender is removed, and forgets it, so
224
+ # that the next write connects again over TCP, or opens a new socket over UDP. The local syslog is left
225
+ # open, since ::Syslog is shared by the whole process. An error closing it is reported to the internal
226
+ # logger, rather than raised.
227
+ #
228
+ # Over TCP, in a forked child that has not reopened, such as one that removes the appender before its
229
+ # reopen has run, it forgets the client it inherited instead, without closing its connection, which
230
+ # belongs to the parent (see #reopen).
231
+ def close
232
+ forget_inherited if @protocol == :tcp
233
+ close_remote_syslog(@remote_syslog)
234
+ ensure
235
+ @remote_syslog = nil
236
+ end
237
+
238
+ # Write the log using the specified protocol and server. Connects over TCP, or opens a socket over UDP,
239
+ # first when the appender has none: after #close, or over TCP when connecting failed as it was reopened
240
+ # after a fork.
194
241
  def log(log)
195
242
  case @protocol
196
243
  when :syslog
197
244
  # Since the Ruby Syslog API supports sprintf format strings, double up all existing '%'
198
- message = formatter.call(log, self).gsub "%", "%%"
245
+ message = format_log(log).gsub "%", "%%"
199
246
  ::Syslog.log @level_map[log.level], message
200
247
  when :tcp
201
- @remote_syslog.retry_on_connection_failure { @remote_syslog.write("#{formatter.call(log, self)}\r\n") }
248
+ client = @remote_syslog || connect_tcp
249
+ client.retry_on_connection_failure { client.write("#{format_log(log)}\r\n") }
202
250
  when :udp
203
- @remote_syslog.send(formatter.call(log, self), 0, @server, @port)
251
+ (@remote_syslog ||= UDPSocket.new).send(format_log(log), 0, @server, @port)
204
252
  else
205
253
  raise "Unsupported protocol: #{protocol}"
206
254
  end
@@ -212,17 +260,86 @@ module SemanticLogger
212
260
  @remote_syslog.flush if @remote_syslog.respond_to?(:flush)
213
261
  end
214
262
 
263
+ # Over UDP, a log message too large for a datagram (Errno::EMSGSIZE) cannot be sent by retrying.
264
+ def message_error?(exception)
265
+ (@protocol == :udp && exception.is_a?(Errno::EMSGSIZE)) || super
266
+ end
267
+
215
268
  # Returns [SemanticLogger::Formatters::Base] default formatter for this Appender
216
269
  # depending on the protocol selected
217
270
  def default_formatter
218
271
  if protocol == :syslog
219
272
  # Format is text output without the time.
220
273
  # Escape control characters so untrusted log data cannot forge syslog entries.
221
- SemanticLogger::Formatters::Default.new(time_format: :notime, escape_control_chars: true)
274
+ # Exception details are off, as with the remote syslog formatters, so existing records do not change.
275
+ SemanticLogger::Formatters::Default.new(
276
+ time_format: :notime, escape_control_chars: true, log_exception_details: false
277
+ )
222
278
  else
223
279
  SemanticLogger::Formatters::Syslog.new(facility: facility, level_map: level_map, max_size: max_size)
224
280
  end
225
281
  end
282
+
283
+ # The formatters that build remote syslog packets, and so need this appender's facility, level map,
284
+ # and maximum packet size.
285
+ PACKET_FORMATTERS = %i[syslog syslog_cee].freeze
286
+ private_constant :PACKET_FORMATTERS
287
+
288
+ # The url without any credentials. See Subscriber#inspect.
289
+ def inspect_details
290
+ "url=#{Utils.redacted_url(url).inspect}"
291
+ end
292
+
293
+ private
294
+
295
+ # Returns [Net::TCPClient] a new client, connected to the server, after making it the appender's. Records
296
+ # the process that built it, which owns its connection (see #reopen).
297
+ def connect_tcp
298
+ @remote_syslog = Net::TCPClient.new(**tcp_client_options)
299
+ # Use the local logger for @remote_syslog so errors with the remote logger can be recorded locally.
300
+ @remote_syslog.logger = logger
301
+ @pid = ::Process.pid
302
+ @remote_syslog
303
+ end
304
+
305
+ # In a child process, forgets the TCP client built in the parent before a fork, and then closes the child's
306
+ # copy of its socket's file descriptor, without a TLS shutdown: SSLSocket#to_io is the TCPSocket under it.
307
+ # See #reopen.
308
+ def forget_inherited
309
+ return if @pid == ::Process.pid
310
+
311
+ inherited = @remote_syslog
312
+ @remote_syslog = nil
313
+ socket = inherited&.socket&.to_io
314
+ socket.close unless socket.nil? || socket.closed?
315
+ end
316
+
317
+ # Closes the given TCP client or UDP socket, if any: the one that a reopen replaced, when replaced: is true.
318
+ # Reports an error to the internal logger as a warning, rather than raising it.
319
+ def close_remote_syslog(remote_syslog, replaced: false)
320
+ remote_syslog&.close
321
+ rescue StandardError => e
322
+ logger.warn("Could not close the connection to the syslog server#{' that a reopen replaced' if replaced}", e)
323
+ end
324
+
325
+ # Returns [Hash] a copy of the options given as tcp_client: (see Subscriber#copy_options), with the server
326
+ # from the url, for a new Net::TCPClient, since it takes handshake_timeout: out of the ssl: Hash it is
327
+ # given: each client gets a copy of its own, which keeps the timeout for the next one, such as after a
328
+ # reopen.
329
+ def tcp_client_options
330
+ copy_options(@tcp_client_options).merge(server: "#{@server}:#{@port}")
331
+ end
332
+
333
+ # Returns the supplied formatter, with this appender's facility, level map, and
334
+ # maximum packet size added when it names one of the PACKET_FORMATTERS, so that they are not
335
+ # silently ignored. Options in a
336
+ # `{syslog: {...}}` Hash take precedence. A formatter instance keeps its own settings.
337
+ def with_packet_options(formatter)
338
+ name, options = formatter.is_a?(Hash) ? formatter.first : [formatter, {}]
339
+ return formatter unless name.respond_to?(:to_sym) && PACKET_FORMATTERS.include?(name.to_sym)
340
+
341
+ {name.to_sym => {facility: facility, level_map: level_map, max_size: max_size}.merge(options || {})}
342
+ end
226
343
  end
227
344
  end
228
345
  end