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 @@ module SemanticLogger
12
12
  # `SemanticLogger.add_appender(appender: :elasticsearch, ...)` or
13
13
  # `appender: :opensearch`, never by referencing this class directly.
14
14
  class ElasticsearchBase < SemanticLogger::Subscriber
15
+ # The most groups of failures that one report of a bulk request lists (see #report_failures).
16
+ MAX_REPORTED_FAILURES = 10
17
+ # The most characters of each reason that the report writes: a reason can repeat a whole value,
18
+ # as the "For input string" of a number that could not be parsed does.
19
+ MAX_REPORTED_REASON = 500
20
+ # The seconds to wait before each time that the entries the server rejected with status 429 are
21
+ # sent again (see #bulk_write): three times, after 0.2, 0.4, then 0.8 seconds, so waits of at
22
+ # most 1.4 seconds for a request, plus up to 3 more bulk requests. Kept short, since waiting
23
+ # holds up the thread that writes the entries.
24
+ RESEND_DELAYS = [0.2, 0.4, 0.8].freeze
25
+ private_constant :MAX_REPORTED_FAILURES, :MAX_REPORTED_REASON, :RESEND_DELAYS
26
+
15
27
  attr_accessor :url, :index, :date_pattern, :client, :flush_interval, :timeout_interval, :batch_size,
16
28
  :client_args
17
29
 
@@ -29,6 +41,12 @@ module SemanticLogger
29
41
  # if you want monthly indexes ('%Y.%m') or weekly ('%Y.%W').
30
42
  # Default: '%Y.%m.%d'
31
43
  #
44
+ # data_stream: [true|false]
45
+ # Write to the data stream named by `index:`, with `create` actions,
46
+ # rather than to a daily index: `date_pattern:` is not used, and the
47
+ # default formatter writes the time under `@timestamp`.
48
+ # Default: false
49
+ #
32
50
  # type: [String]
33
51
  # Deprecated and ignored. Document `_type` has been unused since
34
52
  # Elasticsearch 7 and is ignored by OpenSearch. Passing it logs a
@@ -36,12 +54,15 @@ module SemanticLogger
36
54
  #
37
55
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
38
56
  # Override the log level for this appender.
39
- # Default: SemanticLogger.default_level
57
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
58
+ # filters by its own level.
40
59
  #
41
60
  # formatter: [Object|Proc|Symbol|Hash]
42
61
  # An instance of a class that implements #call, or a Proc to be used to format
43
- # the output from this appender
44
- # Default: :raw_json (See: #call)
62
+ # the output from this appender. It returns the document, as a Hash, or as a
63
+ # String of JSON.
64
+ # Default: :raw, with an ISO 8601 time under `timestamp`, or `@timestamp` with
65
+ # `data_stream: true`.
45
66
  #
46
67
  # filter: [Regexp|Proc]
47
68
  # RegExp: Only include log messages where the class name matches the supplied.
@@ -57,6 +78,10 @@ module SemanticLogger
57
78
  # Name of this application to appear in log messages.
58
79
  # Default: SemanticLogger.application
59
80
  #
81
+ # metrics: [true|false]
82
+ # Whether to also index metric-only entries: a metric without a message or an exception.
83
+ # Default: false
84
+ #
60
85
  # Client Parameters (passed through to the backing client):
61
86
  # url: [String]
62
87
  # Fully qualified address to the service.
@@ -64,9 +89,13 @@ module SemanticLogger
64
89
  #
65
90
  # hosts: [String|Hash|Array]
66
91
  # Single host passed as a String or Hash, or multiple hosts
67
- # passed as an Array; `host` or `url` keys are also valid.
92
+ # passed as an Array. A Hash takes the keys `host`, `port`,
93
+ # `scheme`, `user`, `password`, and `path`.
68
94
  # Note:
69
95
  # :url above is ignored when supplying this option.
96
+ # A `host:` passed to the appender itself, outside the Hash, is
97
+ # not a server: it is the host name written in each log entry,
98
+ # see `host:` above.
70
99
  #
71
100
  # resurrect_after [Float]
72
101
  # After how many seconds a dead connection should be tried again.
@@ -131,13 +160,13 @@ module SemanticLogger
131
160
  environment: nil,
132
161
  host: nil,
133
162
  data_stream: false,
163
+ metrics: false,
134
164
  **client_args,
135
165
  &)
136
166
  if type
137
- Kernel.warn(
167
+ Deprecation.warn(
138
168
  "The Elasticsearch/OpenSearch appender `type:` parameter is deprecated and will be removed in v6. " \
139
- "Document `_type` has been unused since Elasticsearch 7 and is ignored by OpenSearch.",
140
- category: :deprecated
169
+ "Document `_type` has been unused since Elasticsearch 7 and is ignored by OpenSearch."
141
170
  )
142
171
  end
143
172
 
@@ -150,31 +179,38 @@ module SemanticLogger
150
179
  @data_stream = data_stream
151
180
 
152
181
  super(level: level, formatter: formatter, filter: filter, application: application,
153
- environment: environment, host: host, metrics: false, &)
182
+ environment: environment, host: host, metrics: metrics, &)
154
183
  reopen
155
184
  end
156
185
 
186
+ # The url is left to the client gem to parse, since it also takes a comma separated list of
187
+ # urls, an Array of them, or hosts without a scheme.
157
188
  def reopen
158
- @client = client_class.new(@client_args)
189
+ @client = Utils.without_url_in_errors(option: ":url or :hosts") { client_class.new(@client_args) }
159
190
  end
160
191
 
161
- # Log to the index for today
192
+ # Log to the index for today, or to the data stream.
162
193
  def log(log)
163
- bulk_payload = formatter.call(log, self)
164
- bulk_write([bulk_index(log), bulk_payload])
194
+ bulk_write([bulk_entry(log)])
165
195
  true
166
196
  end
167
197
 
168
198
  def batch(logs)
169
- messages = []
170
- logs.each do |log|
171
- messages << bulk_index(log) << formatter.call(log, self)
172
- end
199
+ bulk_write(logs.map { |log| bulk_entry(log) })
200
+ true
201
+ end
173
202
 
174
- bulk_write(messages)
203
+ # The whole batch is formatted into a single bulk request before anything is sent.
204
+ def batch_all_or_nothing?
175
205
  true
176
206
  end
177
207
 
208
+ # The url without its credentials, and the index. See Subscriber#inspect.
209
+ def inspect_details
210
+ url_detail = @client_args.key?(:url) ? "url=#{Utils.redacted_url(url).inspect} " : ""
211
+ "#{url_detail}index=#{index.inspect}"
212
+ end
213
+
178
214
  private
179
215
 
180
216
  # The backing client class, e.g. ::Elasticsearch::Client or ::OpenSearch::Client.
@@ -182,25 +218,182 @@ module SemanticLogger
182
218
  raise NotImplementedError, "#{self.class} must implement #client_class"
183
219
  end
184
220
 
185
- def bulk_write(messages)
186
- bulk_result =
187
- if @data_stream
188
- @client.bulk(index: index, body: messages)
189
- else
190
- @client.bulk(body: messages)
221
+ # Returns [Array] the entry of a bulk request for the log message: its action, and its document
222
+ # (see #bulk_line).
223
+ def bulk_entry(log)
224
+ [bulk_index(log), bulk_line(log)]
225
+ end
226
+
227
+ # Returns [String] the log message formatted as a bulk line, serialized by Utils.to_json
228
+ # and handed to the client as a String. The client gem's serializer writes Infinity and NaN
229
+ # as bare words, which is not JSON, and does not repair invalid UTF-8, a structure nested too
230
+ # deeply, or a Struct (written through its #inspect), so such an entry was dropped or its
231
+ # objects' instance variables were written. Serializing is part of formatting, so an error
232
+ # doing so discards the message rather than stalling the appender (see #format_log). A
233
+ # formatter that returns a String is taken to have serialized the line itself.
234
+ def bulk_line(log)
235
+ format_log(log) { |document| document.is_a?(String) ? document : Utils.to_json(document) }
236
+ end
237
+
238
+ # Sends the entries in one bulk request, then sends again those that the server rejected with
239
+ # status 429 (see #resend_rejected). The entries still not indexed after that, for this or any
240
+ # other reason, are reported and discarded (see #report_failures).
241
+ #
242
+ # The other entries were indexed, so an error raised while sending the rejected ones again,
243
+ # such as a timeout, is reported with the failures, rather than raised, which would count every
244
+ # entry as discarded.
245
+ def bulk_write(entries)
246
+ failed = bulk_failures(entries)
247
+ return if failed.empty?
248
+
249
+ begin
250
+ resend_rejected(entries, failed)
251
+ rescue StandardError => e
252
+ error = e
253
+ end
254
+ report_failures(failed.values, entries.size, error) unless failed.empty?
255
+ end
256
+
257
+ # Sends again the entries that the server rejected with status 429, since its write queue was
258
+ # full, so that they are likely to be indexed a little later. Only those entries are sent again,
259
+ # so that none is indexed twice. They are sent up to RESEND_DELAYS.size more times, after a
260
+ # growing wait, which holds up the thread writing the entries: the appender's own thread when it
261
+ # writes in batches, as it does by default, or with `async: true`. Otherwise it is the thread
262
+ # that writes to every appender, or with SemanticLogger.sync!, the thread that logged, and every
263
+ # other thread that logs waits for it.
264
+ #
265
+ # `failed` holds the result of each entry not indexed, by its position in `entries` (see
266
+ # #bulk_failures). The result of an entry sent again replaces it, and an entry then indexed is
267
+ # removed.
268
+ def resend_rejected(entries, failed)
269
+ RESEND_DELAYS.each do |delay|
270
+ resend = failed.keys.select { |position| failed[position]["status"].to_i == 429 }
271
+ break if resend.empty?
272
+
273
+ sleep(delay)
274
+ again = bulk_failures(resend.map { |position| entries[position] })
275
+ resend.each_with_index do |position, resent|
276
+ if again.key?(resent)
277
+ failed[position] = again[resent]
278
+ else
279
+ failed.delete(position)
280
+ end
191
281
  end
282
+ end
283
+ end
192
284
 
193
- return unless bulk_result["errors"]
285
+ # Sends the entries in one bulk request, serializing their actions; their documents already
286
+ # are (see #bulk_line).
287
+ #
288
+ # Returns [Hash{Integer => Hash}] the result of each entry that was not indexed, by its
289
+ # position in `entries`. The response has an item for each entry, in order, under the name of
290
+ # its action, such as
291
+ # `{"index" => {"_index" => ..., "status" => 400, "error" => {"type" => ..., "reason" => ...}}}`,
292
+ # without the document. An entry failed when its result has an error, or a status of 300 or
293
+ # above: an `index` action succeeds with 201 (created) or 200 (updated), and a `create` action
294
+ # with 201.
295
+ def bulk_failures(entries)
296
+ body = entries.flat_map { |action, document| [action.to_json, document] }
297
+ bulk_result = @data_stream ? @client.bulk(index: index, body: body) : @client.bulk(body: body)
298
+ return {} unless bulk_result["errors"]
299
+
300
+ failures = {}
301
+ bulk_result["items"].each_with_index do |item, position|
302
+ result = item.values.first
303
+ failures[position] = result if result.key?("error") || result["status"].to_i >= 300
304
+ end
305
+ failures
306
+ end
307
+
308
+ # Reports to the internal logger the results of the entries of a bulk request that were not
309
+ # indexed, of `total` entries, which are discarded (see #bulk_write), with the error that
310
+ # stopped sending them again, if any. The failures are grouped by their kind (see
311
+ # #bulk_failure_kind), since the reasons for one kind differ by each entry's id and value, so
312
+ # that a batch whose entries all fail the same way is reported in a short line. Only the first
313
+ # MAX_REPORTED_FAILURES groups are listed.
314
+ def report_failures(failed, total, error = nil)
315
+ groups = failed.group_by { |result| bulk_failure_kind(result) }
316
+ listed = groups.first(MAX_REPORTED_FAILURES).map do |kind, results|
317
+ bulk_failure(kind, results.first["error"], results.size)
318
+ end
319
+ others = groups.values.drop(MAX_REPORTED_FAILURES)
320
+ unless others.empty?
321
+ listed << "and #{others.size} other failure#{'s' unless others.size == 1} " \
322
+ "(#{bulk_entries(others.sum(&:size))})"
323
+ end
324
+
325
+ message = "#{failed.size} of #{total} log entries were not indexed, and are discarded: #{listed.join('; ')}"
326
+ logger.error(message, error)
327
+ end
328
+
329
+ # Returns [Array] the kind of failure of an entry, from the result of its action: its status,
330
+ # error type, and index, and the type of the innermost error that caused it, so that a number
331
+ # and a date that could not be parsed, both a mapping error, are told apart. An error that is a
332
+ # String, as from Elasticsearch 1.x, has no type.
333
+ def bulk_failure_kind(result)
334
+ error = result["error"]
335
+ return [result["status"], nil, result["_index"], nil] unless error.is_a?(Hash)
336
+
337
+ [result["status"], error["type"], result["_index"], bulk_causes(error).last&.fetch("type", nil)]
338
+ end
339
+
340
+ # Returns [String] a kind of failure of the given number of entries: its status, error type,
341
+ # and index, then the error of the first, as an example when there are others.
342
+ def bulk_failure(kind, error, count)
343
+ status, type, index = kind
344
+ failure = [status, type, "in #{index}"].compact.join(" ")
345
+ failure += " (#{bulk_entries(count)})" if count > 1
346
+ reason = bulk_error_reason(error)
347
+ return failure unless reason
348
+
349
+ "#{failure}#{', e.g.' if count > 1}: #{reason}"
350
+ end
351
+
352
+ # Returns [String] the reason for an error, followed by each error that caused it, such as the
353
+ # parser's error under a mapping error's "failed to parse", or nil when it has none. An error
354
+ # that is a String is its reason. A cause without a reason is written as its type alone.
355
+ def bulk_error_reason(error)
356
+ return bulk_reason_text(error) unless error.is_a?(Hash)
357
+
358
+ reasons = [bulk_reason_text(error["reason"])]
359
+ bulk_causes(error).each do |cause|
360
+ reason = bulk_reason_text(cause["reason"])
361
+ reasons << (reason ? "caused by #{cause['type']}: #{reason}" : "caused by #{cause['type']}")
362
+ end
363
+ reasons.compact!
364
+ reasons.join(", ") unless reasons.empty?
365
+ end
366
+
367
+ # Returns [Array<Hash>] the errors that caused this one, from the first to the innermost.
368
+ def bulk_causes(error)
369
+ causes = []
370
+ cause = error
371
+ causes << cause while (cause = cause["caused_by"]).is_a?(Hash)
372
+ causes
373
+ end
374
+
375
+ # Returns [String] a reason as the report writes it, or nil when there is none: its first line
376
+ # only, since the JSON parser adds the error's location on the next, with part of the document;
377
+ # cut to MAX_REPORTED_REASON characters, followed by "..."; and inspected, since it can repeat a
378
+ # value of the entry, so that a control character in that value, such as a line break, cannot
379
+ # forge a line of the log.
380
+ def bulk_reason_text(reason)
381
+ text = reason.to_s.partition("\n").first
382
+ return if text.empty?
383
+ return text.inspect if text.size <= MAX_REPORTED_REASON
384
+
385
+ "#{text[0, MAX_REPORTED_REASON].inspect}..."
386
+ end
194
387
 
195
- failed = bulk_result["items"].reject { |x| x["status"] == 201 }
196
- logger.error("#{self.class.name}: Write failed. Messages discarded. : #{failed}")
388
+ # Returns [String] the number of entries, such as "1 entry" or "3 entries".
389
+ def bulk_entries(count)
390
+ count == 1 ? "1 entry" : "#{count} entries"
197
391
  end
198
392
 
199
393
  def bulk_index(log)
200
- expanded_index_name = log.time.strftime("#{index}-#{date_pattern}")
201
394
  return {"create" => {}} if @data_stream
202
395
 
203
- {"index" => {"_index" => expanded_index_name}}
396
+ {"index" => {"_index" => log.time.strftime("#{index}-#{date_pattern}")}}
204
397
  end
205
398
 
206
399
  def default_formatter
@@ -3,7 +3,8 @@ require "date"
3
3
  #
4
4
  # Note:
5
5
  # * Other than in very low volume environments it is recommended to rather use the Elasticsearch appender,
6
- # since it supports bulk logging.
6
+ # since it supports bulk logging. This appender cannot be batched: with `batch: true`, add_appender raises
7
+ # ArgumentError (see #batch_refusal).
7
8
  #
8
9
  # Example:
9
10
  # SemanticLogger.add_appender(
@@ -31,7 +32,8 @@ module SemanticLogger
31
32
  #
32
33
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
33
34
  # Override the log level for this appender.
34
- # Default: SemanticLogger.default_level
35
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
36
+ # filters by its own level.
35
37
  #
36
38
  # formatter: [Object|Proc|Symbol|Hash]
37
39
  # An instance of a class that implements #call, or a Proc to be used to format
@@ -57,10 +59,9 @@ module SemanticLogger
57
59
  **http_args,
58
60
  &)
59
61
  if type
60
- Kernel.warn(
62
+ Deprecation.warn(
61
63
  "The Elasticsearch/OpenSearch appender `type:` parameter is deprecated and will be removed in v6. " \
62
- "Document `_type` has been unused since Elasticsearch 7 and is ignored by OpenSearch.",
63
- category: :deprecated
64
+ "Document `_type` has been unused since Elasticsearch 7 and is ignored by OpenSearch."
64
65
  )
65
66
  end
66
67
 
@@ -73,13 +74,29 @@ module SemanticLogger
73
74
 
74
75
  # Log to the index for today.
75
76
  def log(log)
76
- post(formatter.call(log, self), log.time.strftime(@logging_path))
77
+ post(format_log(log), log.time.strftime(@logging_path))
77
78
  end
78
79
 
79
80
  # Deletes all log data captured for a day.
80
81
  def delete_all(date = Date.today)
81
82
  delete(date.strftime(@request_path))
82
83
  end
84
+
85
+ # Elasticsearch indexes a batch of documents only through its bulk API, which the :elasticsearch
86
+ # appender uses. The #batch inherited from Appender::Http posts the batch as a JSON array to the
87
+ # url's own path, such as `/`, which Elasticsearch rejects, so add_appender refuses to batch it.
88
+ #
89
+ # Answers only while that #batch is the one in use (see Subscriber#batch_defined_by?), so that a
90
+ # subclass with a #batch of its own, such as one that posts the batch to the bulk API, is batched
91
+ # as before. One whose #batch calls super still posts a JSON array, so it defines its own
92
+ # #batch_refusal.
93
+ def batch_refusal
94
+ return unless batch_defined_by?(Http)
95
+
96
+ "Elasticsearch indexes a batch of entries only through its bulk API, which this appender does not " \
97
+ "use. Use appender: :elasticsearch to send the entries in batches, or add this appender without " \
98
+ "batch: true."
99
+ end
83
100
  end
84
101
  end
85
102
  end
@@ -10,6 +10,15 @@ module SemanticLogger
10
10
  :reopen_period, :reopen_count, :reopen_size, :permissions
11
11
  attr_reader :log_count, :log_size, :current_file_name, :reopen_at
12
12
 
13
+ # With permissions, the log file is opened without following a symbolic link, so that a link
14
+ # planted in the log directory can neither create nor open the file it points at, without
15
+ # blocking, so that a planted FIFO fails to open instead of waiting for a reader, and without
16
+ # becoming the controlling terminal.
17
+ SECURE_OPEN_FLAGS = ::File::NOFOLLOW | ::File::NONBLOCK | ::File::NOCTTY
18
+ # Seconds to wait before opening a refused log file again.
19
+ REFUSED_RETRY_INTERVAL = 5
20
+ private_constant :SECURE_OPEN_FLAGS, :REFUSED_RETRY_INTERVAL
21
+
13
22
  # Create an appender to log to a named file.
14
23
  #
15
24
  # Parameters
@@ -47,7 +56,8 @@ module SemanticLogger
47
56
  #
48
57
  # :level [:trace | :debug | :info | :warn | :error | :fatal]
49
58
  # Override the log level for this appender.
50
- # Default: SemanticLogger.default_level
59
+ # Default: none (:trace), so it writes every entry that a logger emits; each logger
60
+ # filters by its own level.
51
61
  #
52
62
  # :formatter: [Object|Proc]
53
63
  # An instance of a class that implements #call, or a Proc to be used to format
@@ -77,7 +87,12 @@ module SemanticLogger
77
87
  # Octal file permissions to apply to the log file.
78
88
  # Log files frequently contain sensitive information, so restrict access
79
89
  # by supplying for example `0o640` (owner read/write, group read).
80
- # Applied both when the file is created and to an existing log file.
90
+ # Applied both when the file is created and to an existing log file, which must be
91
+ # a regular file owned by the process, with a single hard link, that the file_name
92
+ # names directly rather than through a symbolic link. Nothing is written to any
93
+ # other file, or when the file cannot be opened: the appender raises IOError when it
94
+ # is created, and when the file is later reopened, it reports why and writes nothing
95
+ # until the file is fixed, trying again every few seconds.
81
96
  # Default: nil (use the process umask, the standard Ruby behavior)
82
97
  #
83
98
  # :retry_count [Integer]
@@ -121,7 +136,7 @@ module SemanticLogger
121
136
  # Example
122
137
  # require "semantic_logger"
123
138
  #
124
- # # Enable trace level logging
139
+ # # Log :info and above
125
140
  # SemanticLogger.default_level = :info
126
141
  #
127
142
  # # Log to a file
@@ -153,45 +168,34 @@ module SemanticLogger
153
168
 
154
169
  # Open the file at creation time so that misconfiguration (bad directory,
155
170
  # insufficient permissions, ...) raises immediately in SemanticLogger.add_appender,
156
- # instead of surfacing later on the appender thread via the internal logger.
157
- reopen
171
+ # instead of surfacing later on the appender thread via the internal logger. With
172
+ # permissions, a refused log file raises IOError (see #open_with_permissions).
173
+ raise(IOError, refusal_message, cause: @refusal_cause) unless reopen
158
174
  end
159
175
 
160
176
  # After forking an active process call #reopen to re-open
161
177
  # open the file handles etc to resources.
162
178
  def reopen
163
- begin
164
- @file&.close
165
- rescue StandardError
166
- nil
167
- end
179
+ close_quietly(@file)
168
180
 
169
181
  self.current_file_name = apply_format_directives(file_name)
170
- if ::File.directory?(file_name)
182
+ # With permissions, a directory is refused when it fails to open, like any other file.
183
+ if !permissions && ::File.directory?(current_file_name)
171
184
  raise(ArgumentError, "The supplied log file_name: #{current_file_name} is already a directory.")
172
185
  end
173
186
 
174
187
  self.log_count = 0
175
- if append && reopen_size && ::File.exist?(current_file_name)
176
- self.log_size = ::File.size(current_file_name)
177
- self.log_size = 0 if log_size >= reopen_size
178
- else
179
- self.log_size = 0
180
- end
188
+ # File.size? rather than File.size, since the file can be removed at any time.
189
+ size = ::File.size?(current_file_name) if append && reopen_size
190
+ self.log_size = size && size < reopen_size ? size : 0
181
191
 
182
192
  self.reopen_at = reopen_period ? next_reopen_period(reopen_period) : nil
183
193
 
184
194
  options = ::File::WRONLY | ::File::CREAT
185
195
  options |= ::File::APPEND if append
186
- @file =
187
- if permissions
188
- ::File.open(current_file_name, options, permissions)
189
- else
190
- ::File.open(current_file_name, options)
191
- end
192
- # File.open only applies the permissions when creating the file, so also
193
- # enforce them on an already existing log file.
194
- @file.chmod(permissions) if permissions
196
+ @file = permissions ? open_with_permissions(options) : ::File.open(current_file_name, options)
197
+ return unless @file
198
+
195
199
  # Force all log entries to write immediately without buffering
196
200
  # Allows multiple processes to write to the same log file simultaneously
197
201
  @file.sync = true
@@ -203,21 +207,28 @@ module SemanticLogger
203
207
  # Since only one appender thread will be writing to the file at a time
204
208
  # it is not necessary to protect access to the file with a semaphore.
205
209
  def log(log)
206
- reopen if time_to_reopen?
210
+ # Read once, since #reopen can be called from another thread meanwhile.
211
+ file = time_to_reopen? ? reopen : @file
212
+ return refused unless file
207
213
 
214
+ # Formatted once, outside the retry below: reopening the file cannot fix the content.
215
+ line = format_log(log) { |text| TextOutput.line(text) }
208
216
  count = 0
209
217
  begin
210
- message = formatter.call(log, self) << "\n"
211
- @file.write(message)
218
+ # The number of bytes written, in the file's `encoding`, as IO#write returns it.
219
+ written = TextOutput.write(file, line)
212
220
  @log_count += 1
213
- @log_size += message.size
221
+ @log_size += written
214
222
  rescue StandardError => e
215
- if count < retry_count
216
- count += 1
217
- reopen
218
- retry
219
- end
220
- raise(e)
223
+ # Nor can it fix text that the file refuses even converted (see TextOutput and
224
+ # #message_error?).
225
+ raise(e) if count >= retry_count || message_error?(e)
226
+
227
+ count += 1
228
+ file = reopen
229
+ return refused unless file
230
+
231
+ retry
221
232
  end
222
233
  true
223
234
  end
@@ -228,18 +239,130 @@ module SemanticLogger
228
239
  @file&.flush
229
240
  end
230
241
 
242
+ # Closes the log file, such as when the appender is removed, and forgets it, so that a write after
243
+ # it opens the file again, whatever the retry_count. An error closing it, such as EIO when the
244
+ # file's last writes did not reach a network file system, is reported rather than raised.
245
+ def close
246
+ @file&.close
247
+ rescue StandardError => e
248
+ logger.warn("Could not close the log file #{current_file_name}", e)
249
+ ensure
250
+ @file = nil
251
+ @refused_retry_at = nil
252
+ end
253
+
254
+ # See Subscriber#inspect.
255
+ def inspect_details
256
+ "file_name=#{file_name.inspect}"
257
+ end
258
+
231
259
  private
232
260
 
233
261
  attr_writer :log_count, :log_size, :current_file_name, :reopen_at
234
262
 
263
+ # Opens the log file and applies the permissions to it, when it is safe to do so (see
264
+ # #permissions_refusal). Returns the open file, or nil after closing it and recording why it is
265
+ # refused, so that nothing is written to it.
266
+ #
267
+ # Changing the permissions of a file that another name links to could loosen them on an
268
+ # unrelated file, such as a private key linked into a shared log directory. Writing log messages
269
+ # to a file that this process does not own, or that another name links to, would let whoever
270
+ # controls it read them, despite the permissions asked for. So with permissions, the appender
271
+ # fails closed: it raises when it is created (see #initialize), and when the file is later
272
+ # reopened, on a rotation, a fork, or a write retry, it stops writing and reports why (see
273
+ # #refused) until the file is fixed (see #refused_retry_due?).
274
+ def open_with_permissions(options)
275
+ file = ::File.open(current_file_name, options | SECURE_OPEN_FLAGS, permissions)
276
+ reason = permissions_refusal(file)
277
+ if reason
278
+ close_quietly(file)
279
+ return refuse(reason)
280
+ end
281
+
282
+ file.chmod(permissions)
283
+ @refusal = @refusal_cause = @reported_refusal = nil
284
+ file
285
+ rescue SystemCallError => e
286
+ close_quietly(file)
287
+ refuse(open_refusal(e), e)
288
+ end
289
+
290
+ # Records why the log file is refused, and returns nil.
291
+ def refuse(reason, cause = nil)
292
+ @refusal = reason
293
+ @refusal_cause = cause
294
+ @refused_retry_at = monotonic_time + REFUSED_RETRY_INTERVAL
295
+ nil
296
+ end
297
+
298
+ # Reports why log messages are not being written to the log file, once for each file and
299
+ # reason, and returns false.
300
+ def refused
301
+ refusal = [current_file_name, @refusal]
302
+ unless @reported_refusal == refusal
303
+ @reported_refusal = refusal
304
+ logger.error(refusal_message)
305
+ end
306
+ false
307
+ end
308
+
309
+ def refusal_message
310
+ "Not writing to the log file #{current_file_name}: #{@refusal}"
311
+ end
312
+
313
+ # Returns why the log file could not be opened with permissions.
314
+ def open_refusal(error)
315
+ return "it is a symbolic link" if error.is_a?(Errno::ELOOP) && ::File.symlink?(current_file_name)
316
+
317
+ "it could not be opened (#{error.message})"
318
+ end
319
+
320
+ # Returns why the permissions must not be applied to the open log file, nor log messages
321
+ # written to it, or nil when they can.
322
+ #
323
+ # It must be a regular file owned by this process, with a single hard link, since a hard link
324
+ # planted in the log directory is otherwise indistinguishable from the file it links to. The
325
+ # path must also still name it, so that swapping the path after opening cannot redirect the
326
+ # log messages.
327
+ def permissions_refusal(file)
328
+ stat = file.stat
329
+ path_stat = ::File.lstat(current_file_name)
330
+ return "it is not a regular file" unless stat.file?
331
+ return "it is not owned by this process" unless stat.uid == ::Process.euid
332
+ return "it has more than one hard link" unless stat.nlink == 1
333
+ return "it changed after it was opened" unless path_stat.dev == stat.dev && path_stat.ino == stat.ino
334
+
335
+ nil
336
+ rescue SystemCallError => e
337
+ "it could not be checked (#{e.message})"
338
+ end
339
+
340
+ def close_quietly(file)
341
+ file&.close
342
+ rescue StandardError
343
+ nil
344
+ end
345
+
346
+ def monotonic_time
347
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
348
+ end
349
+
235
350
  def time_to_reopen?
236
- return true unless @file
351
+ return refused_retry_due? unless @file
237
352
 
238
353
  (reopen_count.positive? && (log_count >= reopen_count)) ||
239
354
  (reopen_size.positive? && (log_size >= reopen_size)) ||
240
355
  (reopen_at && (Time.now > reopen_at))
241
356
  end
242
357
 
358
+ # A refused log file is opened again every few seconds, and at the next scheduled reopen,
359
+ # rather than for every message.
360
+ def refused_retry_due?
361
+ return true unless @refused_retry_at
362
+
363
+ monotonic_time >= @refused_retry_at || (reopen_at && Time.now > reopen_at)
364
+ end
365
+
243
366
  def apply_format_directives(file_name)
244
367
  return file_name unless file_name.include?("%")
245
368