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
@@ -1,12 +1,19 @@
1
+ # Loaded now rather than autoloaded, since .logger builds one on first use, which can be the first log
2
+ # call of the process, made in a signal trap, where Ruby does not allow a require.
3
+ require "semantic_logger/appender/io"
4
+
1
5
  module SemanticLogger
2
6
  # Thread that submits and processes log requests
3
7
  class Processor < Appender::Async
4
8
  # Allow the internal logger to be overridden from its default of $stderr
5
9
  # Can be replaced with another Ruby logger or Rails logger, but never to
6
10
  # SemanticLogger::Logger itself since it is for reporting problems
7
- # while trying to log to the various appenders
8
- class << self
9
- attr_writer :logger
11
+ # while trying to log to the various appenders (raises ArgumentError)
12
+ #
13
+ # A Ruby or Rails logger is wrapped in an appender (see Appender.internal_logger), so .logger
14
+ # returns that appender. The appenders added from then on report to it.
15
+ def self.logger=(logger)
16
+ @logger = Appender.internal_logger(logger)
10
17
  end
11
18
 
12
19
  # Internal logger for SemanticLogger
@@ -24,10 +31,124 @@ module SemanticLogger
24
31
  attr_reader :appenders
25
32
 
26
33
  def initialize(max_queue_size: 10_000)
27
- @appenders = Appenders.new(self.class.logger.dup)
34
+ @appenders = Appenders.new(self.class.logger.dup)
35
+ # The appenders whose removal was handed over to the worker thread, and not yet done (see #remove),
36
+ # kept here rather than only on the queue, which a forked child replaces. Takes no lock to change.
37
+ @pending_removals = Concurrent::Array.new
38
+ @pid = ::Process.pid
28
39
  super(appender: @appenders, max_queue_size: max_queue_size)
29
40
  end
30
41
 
42
+ # Reopen the appenders, after a fork or within the same process, each on the thread that writes
43
+ # to it, between writes (see Appender::Async#reopen): the worker thread of this processor reopens
44
+ # the appenders (see Appenders#reopen).
45
+ #
46
+ # After a fork, the queue and worker thread of each appender added with async: true or in batches
47
+ # are first replaced on the calling thread, rather than once this processor's worker thread gets
48
+ # to the reopen, so that they are running when this returns, such as for SemanticLogger.stats.
49
+ # That worker thread still asks each of them to reopen its appender, ahead of the entries it
50
+ # hands them. Takes no lock, so that it can be called from a signal trap.
51
+ #
52
+ # In a forked child, the removals handed over to the worker thread that it had not yet done in the
53
+ # parent (see #remove) were on the parent's queue, which the child replaces. So they are handed
54
+ # over again, to the child's worker thread, after the reopen: each such appender, reopened first,
55
+ # then closes only what it built in the child. They count as pending (see #removal_pending?) just
56
+ # before that, so a #remove of one meanwhile returns true while it is still listed, briefly.
57
+ def reopen
58
+ forked = @pid != ::Process.pid
59
+ @pid = ::Process.pid
60
+ appenders.renew_after_fork
61
+ super
62
+ hand_over_pending_removals if forked
63
+ end
64
+
65
+ # Remove the appender from those that this processor writes to, and close it. Returns the result
66
+ # of closing it, or true when it hands the close over to the worker thread (see below).
67
+ #
68
+ # Before closing an appender that it removed, waits until the log messages already queued are
69
+ # written to the other appenders, and those flushed (see #flush), so that none is still being
70
+ # written to it when it is closed, such as a request on its connection that the worker thread is
71
+ # sending.
72
+ #
73
+ # First, when the appender is one of them, and the appenders are to be reopened (see #reopen) but
74
+ # the worker thread has not yet reopened them, such as in a forked child that has not logged
75
+ # since the fork, waits until it has (see QueueProcessor#await_reopen), so that the appender is
76
+ # reopened before it is removed. Its #close then closes only what it built in this process,
77
+ # rather than what it inherited from the parent, which over TLS would end the parent's connection
78
+ # too, for an appender whose #reopen forgets what the parent built, but whose #close does not. An
79
+ # appender added with async: true or in batches is asked to reopen by that reopen, and its own
80
+ # worker thread reopens it before it runs the close.
81
+ #
82
+ # Called on the worker thread itself, such as by an appender as it writes, it closes the appender
83
+ # at once, without waiting, since nothing else writes to it then.
84
+ #
85
+ # Called where it must not wait for the worker thread (see #current_thread_inside?), such as by an
86
+ # appender added with async: true or in batches as it writes, removing itself or another one, it
87
+ # hands the removal over to the worker thread without waiting (see QueueProcessor#hand_over), and
88
+ # returns true, before the appender is closed. Between writes, never while it writes to the
89
+ # appender, once it has written the log messages queued ahead, the worker thread closes the
90
+ # appender, then removes it (see #close_removed). An appender that removed itself is closed once
91
+ # its current write has returned, after the log messages queued for it.
92
+ #
93
+ # The appender stays in the list until it is closed, so that the thread of an appender that
94
+ # removed itself still counts as one that must not wait while it is being closed, and a close of
95
+ # every appender (see #close) that runs first closes it instead. A removal handed over is never
96
+ # what changes the list while the worker thread goes through it, writing a message or closing
97
+ # every appender, since the worker thread itself takes the appender off the list. Until then,
98
+ # #appenders still lists it.
99
+ #
100
+ # Called on any other thread for an appender whose removal was handed over and is not yet done,
101
+ # it leaves the close to that removal, so that the appender is not closed twice: it waits for the
102
+ # log messages queued ahead to be written (see #flush), which, with the removal queued ahead, takes
103
+ # it off the list, and returns true. Not in a forked child that has not reopened this processor,
104
+ # whose queue still holds none of those removals (see #removal_pending?): it closes the appender.
105
+ #
106
+ # Takes no lock, so that it can be called from a signal trap.
107
+ def remove(appender)
108
+ return hand_over_removal(appender) if current_thread_inside?
109
+ return flush || true if removal_pending?(appender)
110
+
111
+ processor.await_reopen if appenders.include?(appender)
112
+ flush if appenders.delete(appender)
113
+ appender.close
114
+ end
115
+
116
+ # Write the log messages already queued to the appenders, then flush them (see
117
+ # QueueProcessor#flush).
118
+ #
119
+ # Returns false at once on the worker thread of an appender added with async: true or in batches,
120
+ # such as by that appender as it writes, rather than wait forever: the worker thread of this
121
+ # processor waits for that thread to flush the appender. Reported once to the internal logger.
122
+ def flush
123
+ return super unless current_thread_inside?
124
+
125
+ refuse_on_appender_thread(:flush)
126
+ end
127
+
128
+ # Flush and close the appenders, then remove them (see Appenders#close).
129
+ #
130
+ # Returns false at once on the worker thread of an appender added with async: true or in batches,
131
+ # as #flush does.
132
+ def close
133
+ return super unless current_thread_inside?
134
+
135
+ refuse_on_appender_thread(:close)
136
+ end
137
+
138
+ # Returns [true|false] whether the calling thread must not wait for a thread that uses this
139
+ # processor, since that thread may be waiting for it: the calling thread is the worker thread of
140
+ # an appender added with async: true or in batches, for which the worker thread of this processor
141
+ # waits, to flush or close it, or for room on its full queue. A message that such a thread logs
142
+ # while the queue of this processor is full is dropped, rather than wait for room, only while
143
+ # this processor's worker thread can be waiting for it: while that appender's own queue is full,
144
+ # or a flush or close of it is waiting (see QueueProcessor#holding_up?).
145
+ #
146
+ # Otherwise false: holding no lock while it queues an entry, this processor never has another
147
+ # thread wait for the calling thread to return from a call to it, even on its own worker thread.
148
+ def current_thread_inside?
149
+ appenders.worker_thread?
150
+ end
151
+
31
152
  # Start the appender thread
32
153
  def start
33
154
  return false if active?
@@ -36,6 +157,11 @@ module SemanticLogger
36
157
  true
37
158
  end
38
159
 
160
+ # Returns [Integer] the number of log messages waiting on the main pipeline queue.
161
+ def queue_size
162
+ queue.size
163
+ end
164
+
39
165
  # Returns [Hash] operational statistics for the logging pipeline.
40
166
  #
41
167
  # queue_size: [Integer] Number of log messages waiting on the main pipeline queue.
@@ -47,7 +173,7 @@ module SemanticLogger
47
173
  # appenders: [Array<Hash>] Per-appender statistics, see Appenders#stats.
48
174
  def stats
49
175
  {
50
- queue_size: queue.size,
176
+ queue_size: queue_size,
51
177
  capped: capped?,
52
178
  max_queue_size: capped? ? max_queue_size : nil,
53
179
  thread_active: active? || false,
@@ -56,5 +182,68 @@ module SemanticLogger
56
182
  appenders: appenders.stats
57
183
  }
58
184
  end
185
+
186
+ private
187
+
188
+ # Hand the removal of the appender over to the worker thread (see #remove), recording it as
189
+ # pending until it is done.
190
+ def hand_over_removal(appender)
191
+ @pending_removals << appender unless @pending_removals.include?(appender)
192
+ processor.hand_over { close_removed(appender) }
193
+ true
194
+ end
195
+
196
+ # Whether the removal of the appender was handed over to the worker thread (see #remove), and is
197
+ # not yet done. Only in the process that handed it over, or a forked child once #reopen has handed
198
+ # it over again: until then, the queue of a forked child holds the parent's entries, which no
199
+ # worker thread of the child runs.
200
+ def removal_pending?(appender) = @pid == ::Process.pid && @pending_removals.include?(appender)
201
+
202
+ # In a forked child, hand over again the removals pending in the parent (see #reopen), for the
203
+ # appenders still listed.
204
+ def hand_over_pending_removals
205
+ @pending_removals.dup.each do |appender|
206
+ next @pending_removals.delete(appender) unless appenders.include?(appender)
207
+
208
+ processor.hand_over { close_removed(appender) }
209
+ end
210
+ end
211
+
212
+ # Close the appender, then remove it from the list, on the worker thread, unless it is no longer
213
+ # listed: a close of every appender (see #close), or another removal, already closed it. Its
214
+ # removal is then no longer pending.
215
+ #
216
+ # Reports an error rather than raise it to the worker thread, as Appenders#close does, whatever
217
+ # its class, since one that is not a StandardError would stop the worker thread for good. Except
218
+ # a stack overflow, which the worker thread must not carry on after: on macOS a second one on the
219
+ # same thread crashes Ruby. It is raised, and a new worker thread carries on (see
220
+ # QueueProcessor#run_command).
221
+ def close_removed(appender)
222
+ return @pending_removals.delete(appender) unless appenders.include?(appender)
223
+
224
+ begin
225
+ appender.close
226
+ rescue SystemStackError
227
+ raise
228
+ rescue Exception => e
229
+ appenders.logger.error "Failed to close appender: #{appender.name}", e
230
+ ensure
231
+ appenders.delete(appender)
232
+ @pending_removals.delete(appender)
233
+ end
234
+ end
235
+
236
+ # Refuse to flush or close on the worker thread of an appender (see #flush), and report it the first
237
+ # time. Returns false.
238
+ def refuse_on_appender_thread(command)
239
+ unless @refused_on_appender_thread
240
+ @refused_on_appender_thread = true
241
+ appenders.logger.warn "SemanticLogger.#{command} was called on the worker thread of an appender " \
242
+ "added with async: true or in batches, such as by that appender as it writes. " \
243
+ "It returns false there, without waiting, since the processor's thread waits " \
244
+ "for that thread. Reported only once."
245
+ end
246
+ false
247
+ end
59
248
  end
60
249
  end
@@ -0,0 +1,140 @@
1
+ module SemanticLogger
2
+ class QueueProcessor
3
+ # Internal: how long the worker thread of a queue processor waits, after it could not write to
4
+ # the destination of its appender, before it writes again, and when it gives up instead.
5
+ #
6
+ # It knows how many times in a row writing has failed, how many times the worker thread may retry
7
+ # before it gives up (async_max_retries), how many requests, such as a flush or close, are
8
+ # waiting for the worker thread to run them, and whether the process is exiting. Each back-off
9
+ # waits a second longer than the one before, except while the worker thread is waited on, by a
10
+ # request or the exiting process, which must not wait out back-offs: then the worker thread does
11
+ # not wait at all, submitting a request or exiting ends the back-off under way, and once the
12
+ # destination fails, the worker thread gives up on the messages queued ahead of the next request
13
+ # (see #give_up?).
14
+ #
15
+ # Requests are submitted from other threads, and from a signal trap, where Ruby does not allow a
16
+ # Mutex to be locked, so it counts them, and waits, on Queues.
17
+ class Backoff
18
+ # Returns [Integer] the number of times the worker thread retries after a failure, before it
19
+ # gives up, or -1 to retry for ever.
20
+ attr_reader :max_retries
21
+
22
+ # Returns [Integer] the number of failures in a row, which is also how many seconds the next
23
+ # back-off waits.
24
+ attr_reader :retry_count
25
+
26
+ def initialize(max_retries)
27
+ @max_retries = max_retries
28
+ @retry_count = 0
29
+ # One entry for each request waiting.
30
+ @requests = Queue.new
31
+ # Holds an entry once a request has been submitted since the back-off under way began. One is
32
+ # enough to end it, so that submitting many requests without a failure does not add up.
33
+ @interrupts = SizedQueue.new(1)
34
+ @exiting = false
35
+ @gave_up = nil
36
+ end
37
+
38
+ # Start counting afresh, once writing succeeds.
39
+ def reset
40
+ @retry_count = 0
41
+ end
42
+
43
+ # Start afresh for a worker thread new to the process, after a fork: it has not failed yet, the
44
+ # requests counted as waiting were on the queue of the parent process, which the child
45
+ # replaces, and the child is not exiting, even when the parent was, such as when another thread
46
+ # forked while the parent flushed at exit.
47
+ def restart
48
+ reset
49
+ @requests.clear
50
+ @exiting = false
51
+ @gave_up = nil
52
+ end
53
+
54
+ # Count a failure. Returns whether the worker thread retries after it, or false once it has
55
+ # retried max_retries times in a row.
56
+ def retry?
57
+ return false unless max_retries == -1 || retry_count < max_retries
58
+
59
+ @retry_count += 1
60
+ true
61
+ end
62
+
63
+ # Returns [Integer|String] the number of retries the worker thread makes at most, for a report.
64
+ def limit = max_retries == -1 ? "unlimited" : max_retries
65
+
66
+ # Waits retry_count seconds, unless the worker thread is waited on, or until it is.
67
+ #
68
+ # The interruptions from before are cleared before it checks whether it is waited on, so that a
69
+ # request submitted, or the process exiting, in between either is seen or interrupts the wait.
70
+ def wait
71
+ @interrupts.clear
72
+ @interrupts.pop(timeout: retry_count) unless waited_on?
73
+ end
74
+
75
+ # Called before a request is added to the queue: it is waiting until #request_done, and ends the
76
+ # back-off under way. Never waits, since an interruption already queued ends it as well.
77
+ def request_submitted
78
+ @requests << true
79
+ @interrupts.push(true, timeout: 0)
80
+ end
81
+
82
+ # Called once for each request submitted, once it has run or will not (see Request#done). The
83
+ # worker thread no longer gives up on the messages queued after it (see #give_up?).
84
+ def request_done
85
+ @requests.pop(timeout: 0)
86
+ @gave_up = nil
87
+ end
88
+
89
+ # Tell it whether the process is exiting: true before the flush at exit, and false once that
90
+ # flush has returned, since a test framework can run its tests in a later at_exit hook. While
91
+ # the process exits, the worker thread is waited on, as though a request were waiting, and the
92
+ # back-off under way ends. Once it no longer exits, the worker thread gives up no more, unless a
93
+ # request is still waiting (see #gave_up). Called from the exiting thread, which may be in a
94
+ # signal trap, so it takes no lock either.
95
+ def exiting=(exiting)
96
+ @exiting = exiting
97
+ if exiting
98
+ @interrupts.push(true, timeout: 0)
99
+ elsif !waited_on?
100
+ @gave_up = nil
101
+ end
102
+ end
103
+
104
+ # Whether the worker thread is waited on: a request, such as a flush or close, is waiting for
105
+ # it to run it, or the process is exiting. It then neither waits out back-offs nor writes again
106
+ # what the destination failed.
107
+ def waited_on? = @exiting || request_waiting?
108
+
109
+ # Whether a request, such as a flush or close, is waiting for the worker thread to run it. The
110
+ # thread that submitted it may be the worker thread of the queue processor that writes to this
111
+ # one's appender, which then waits for this worker thread (see QueueProcessor#holding_up?).
112
+ def request_waiting? = !@requests.empty?
113
+
114
+ # Called once the destination failed. While the worker thread is waited on, it gives up on the
115
+ # messages queued ahead of the next request, such as a flush, and discards them without writing
116
+ # them (see #gave_up), since each could take as long to fail, such as the open_timeout of a
117
+ # server that does not answer. While the process exits, it does so as well before the flush at
118
+ # exit reaches the queue. Once a request has run (see #request_done), it writes the next
119
+ # message once more, even while the process exits, and gives up again if that fails. So
120
+ # returns true, having recorded the exception, for the worker thread to carry on straight
121
+ # away, without backing off or counting a retry. Otherwise returns false.
122
+ def give_up?(exception)
123
+ return false unless waited_on?
124
+
125
+ @gave_up = exception
126
+ true
127
+ end
128
+
129
+ # Returns the exception with which the destination failed while the worker thread was waited
130
+ # on (see #give_up?), while the messages it takes off the queue are to be discarded: until a
131
+ # request has run, or the worker thread is no longer waited on. Otherwise nil.
132
+ def gave_up
133
+ return unless @gave_up
134
+ return @gave_up if waited_on?
135
+
136
+ @gave_up = nil
137
+ end
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,69 @@
1
+ module SemanticLogger
2
+ class QueueProcessor
3
+ # Internal: what became of a batch of log messages whose write raised a message error (see
4
+ # Subscriber#message_error?), as the appender tells from the error, for the worker thread of a
5
+ # queue processor to carry on with: how many of them the destination stored, those to discard,
6
+ # and the parts of the batch to write again.
7
+ #
8
+ # When the appender says which message the destination rejected, having stored those before it
9
+ # (see Subscriber#rejected_entry), those before it were written, it is discarded, and those after
10
+ # it are written again as a batch. Otherwise, when the appender's #batch is all or nothing (see
11
+ # Subscriber#batch_all_or_nothing?), the batch is split in half, and each half written again, so
12
+ # that only the messages at fault are discarded, unless the error would fail any batch (see
13
+ # Subscriber#fails_any_batch?). Any other batch is discarded, since writing it again could write
14
+ # some of its messages twice.
15
+ class BatchFailure
16
+ # Returns [Integer] how many of the messages, from the first, the destination stored.
17
+ attr_reader :written
18
+
19
+ # Returns [Array<Log>] the messages to discard.
20
+ attr_reader :discarded
21
+
22
+ # Returns [Array<Array<Log>>] the parts of the batch to write again, in order.
23
+ attr_reader :parts
24
+
25
+ def initialize(appender, logs, exception)
26
+ @appender = appender
27
+ @exception = exception
28
+ @written = 0
29
+ @discarded = []
30
+ @parts = []
31
+ rejected = rejected_entry(logs)
32
+ if rejected
33
+ after_rejected(logs, rejected)
34
+ elsif logs.size == 1 || !appender.batch_all_or_nothing? || fails_any_batch?
35
+ @discarded = logs
36
+ else
37
+ @parts = logs.each_slice((logs.size + 1) / 2).to_a
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ attr_reader :appender, :exception
44
+
45
+ # The destination stored the messages before the one at position `rejected`, and rejected that
46
+ # one, along with every one after it when the error would fail any batch.
47
+ def after_rejected(logs, rejected)
48
+ @written = rejected
49
+ @discarded = fails_any_batch? ? logs.drop(rejected) : [logs[rejected]]
50
+ rest = logs.drop(rejected + @discarded.size)
51
+ @parts = [rest] unless rest.empty?
52
+ end
53
+
54
+ # Returns [Integer|nil] the position in the batch of the message that the destination
55
+ # rejected, when the appender says so, or nil when it does not, or names no message in the
56
+ # batch. An appender that does not implement #rejected_entry cannot say.
57
+ def rejected_entry(logs)
58
+ rejected = appender.respond_to?(:rejected_entry) && appender.rejected_entry(exception)
59
+ rejected if rejected.is_a?(Integer) && rejected.between?(0, logs.size - 1)
60
+ end
61
+
62
+ # An appender that does not implement #fails_any_batch? has every all or nothing batch split,
63
+ # as before it could say.
64
+ def fails_any_batch?
65
+ appender.respond_to?(:fails_any_batch?) && appender.fails_any_batch?(exception)
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,62 @@
1
+ module SemanticLogger
2
+ class QueueProcessor
3
+ # Internal: the log messages, one or a batch, whose write the destination of the appender failed
4
+ # without storing any of them, held for the worker thread of a queue processor to write again
5
+ # once it has backed off, ahead of the messages on the queue.
6
+ #
7
+ # It knows the messages held, and how many times in a row they have been held again after the
8
+ # destination answered the write with a failure. It holds them again after such an answer at most
9
+ # MAX_RESENDS times, so that messages the destination fails every time, such as a request it
10
+ # answers with a 429 that never clears, are discarded rather than hold up the messages behind
11
+ # them until the worker thread gives up after async_max_retries. A write that never reached the
12
+ # destination, such as one that could not connect, is not counted: the destination has said
13
+ # nothing about these messages, so an outage loses none of them until the worker thread gives up.
14
+ class HeldWrite
15
+ # The most times the same messages are written again after the destination answered that it
16
+ # failed them. A constant rather than an option: it only limits how long one write that keeps
17
+ # failing holds up the queue, while async_max_retries already sets how long the worker thread
18
+ # keeps trying through an outage.
19
+ MAX_RESENDS = 3
20
+
21
+ def initialize
22
+ @logs = nil
23
+ @resends = 0
24
+ end
25
+
26
+ # Holds the messages to write again. `answered` says whether the destination answered the
27
+ # write that failed, rather than never received it, which counts towards MAX_RESENDS. Returns
28
+ # false, without holding them, when the destination answered and they have already been held
29
+ # again MAX_RESENDS times after it did.
30
+ def hold(logs, answered:)
31
+ if answered
32
+ return false if @resends >= MAX_RESENDS
33
+
34
+ @resends += 1
35
+ end
36
+ @logs = logs
37
+ true
38
+ end
39
+
40
+ # Yields the messages held, if any, for the block to write them again. Those the block holds
41
+ # again keep the count; any other messages held later start afresh.
42
+ def resend
43
+ return unless @logs
44
+
45
+ logs = @logs
46
+ @logs = nil
47
+ yield logs
48
+ ensure
49
+ @resends = 0 unless @logs
50
+ end
51
+
52
+ # Forgets the messages held, if any, and returns them, such as when the worker thread gives up
53
+ # on them, or after a fork, when the parent process writes them.
54
+ def release
55
+ logs = @logs
56
+ @logs = nil
57
+ @resends = 0
58
+ logs
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,97 @@
1
+ module SemanticLogger
2
+ class QueueProcessor
3
+ # Internal: the queue on which log messages, and requests such as a flush, wait for the worker
4
+ # thread of a queue processor to take them off.
5
+ #
6
+ # It knows the queue, whether its size is capped, and the process that created it, and adds to
7
+ # it, waiting for room on a full queue or not. After a fork, the child's copy of the queue holds
8
+ # the entries of the parent, which the parent's worker thread writes, so the child replaces it.
9
+ #
10
+ # Also used in a signal trap, where Ruby allows a Queue to wait, but not a Mutex to be locked.
11
+ class Inbox
12
+ # How often, in seconds, a thread waiting for room on the full queue asks whether to keep
13
+ # waiting (see #push), so that it does not wait for ever once nothing makes room.
14
+ WAIT_CHECK_SECONDS = 1
15
+
16
+ # Returns [Queue|SizedQueue] the queue.
17
+ attr_reader :queue
18
+
19
+ # Returns [Integer] the most entries the queue holds, or -1 for no limit.
20
+ attr_reader :max_queue_size
21
+
22
+ def initialize(max_queue_size)
23
+ @max_queue_size = max_queue_size
24
+ create
25
+ end
26
+
27
+ # Returns [true|false] whether the queue has a capped size.
28
+ def capped? = @capped
29
+
30
+ # Returns [true|false] whether the queue is capped, and holds as many entries as it can.
31
+ def full? = @capped && @queue.size >= max_queue_size
32
+
33
+ # Whether this is a child of the process that created the queue, whose copy of the queue then
34
+ # holds that process's entries.
35
+ def forked? = @pid != ::Process.pid
36
+
37
+ # Closes the queue, and creates an empty one, which belongs to this process.
38
+ def recreate
39
+ @queue.close
40
+ create
41
+ end
42
+
43
+ # Add to the `target` queue, the current one by default. Returns whether it was added.
44
+ #
45
+ # A queue that is not capped is never full, and its #push takes no timeout. On a full queue,
46
+ # without `wait`, returns false at once. With `wait`, waits for room while the block returns
47
+ # true, which it is asked as soon as the queue is found full, then every WAIT_CHECK_SECONDS, and
48
+ # returns false once it returns false, such as once the worker thread has stopped for good,
49
+ # since then nothing makes room. The block is not asked when the queue has room.
50
+ def push(item, target = queue, wait:)
51
+ return target.push(item) && true unless capped?
52
+ return true if target.push(item, timeout: 0)
53
+
54
+ loop do
55
+ return false unless wait && yield
56
+ return true if target.push(item, timeout: WAIT_CHECK_SECONDS)
57
+ end
58
+ end
59
+
60
+ # Add the items, in order, without making the calling thread wait for room on a full queue,
61
+ # while the block returns true. Once the queue is full, one new thread adds the rest, in order,
62
+ # waiting for room while the block returns true. Once the block returns false, at once or while
63
+ # that thread waits, the items not yet added are passed to `otherwise` instead, on that thread.
64
+ # Returns true, without waiting. Takes no lock, so that it can be called from a signal trap.
65
+ def push_aside(items, otherwise, &adding)
66
+ rest = items.drop_while { |item| adding.call && push(item, wait: false) }
67
+ return true if rest.empty?
68
+
69
+ Thread.new { otherwise.call(rest.drop_while { |item| adding.call && push(item, wait: true, &adding) }) }
70
+ true
71
+ end
72
+
73
+ # Take the entries of the given class off the queue, and return them, in order. The others are added
74
+ # back, in order, behind any added meanwhile, without waiting for room; yields each one that a thread
75
+ # waiting for room took the place of, so that it is not lost unseen. Takes no lock.
76
+ def take(kind)
77
+ entries = Array.new(@queue.size) { @queue.pop(timeout: 0) }.compact
78
+ taken, others = entries.partition { |entry| entry.is_a?(kind) }
79
+ others.each { |entry| push(entry, wait: false) || (yield(entry) if block_given?) }
80
+ taken
81
+ end
82
+
83
+ private
84
+
85
+ def create
86
+ @pid = ::Process.pid
87
+ if max_queue_size == -1
88
+ @queue = Queue.new
89
+ @capped = false
90
+ else
91
+ @queue = SizedQueue.new(max_queue_size)
92
+ @capped = true
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,56 @@
1
+ module SemanticLogger
2
+ class QueueProcessor
3
+ # Internal: reopens the appender of a queue processor, on its worker thread, once asked.
4
+ #
5
+ # The worker thread asks it between writes, so the appender is never reopened while it is
6
+ # writing, such as a file being closed under a write, or a connection ended under a request.
7
+ # Nor is it reopened on the thread that asks, often a signal trap after a log rotation, where
8
+ # Ruby does not allow a Mutex to be locked, as connecting with a timeout does.
9
+ #
10
+ # It knows whether a reopen has been asked for, and reports a reopen that fails to the internal
11
+ # logger. Asked from any thread, and from a signal trap, so it records that on a Queue.
12
+ class Reopener
13
+ def initialize(appender, reporter)
14
+ @appender = appender
15
+ @reporter = reporter
16
+ @asked = Queue.new
17
+ @reopening = false
18
+ end
19
+
20
+ # Ask for the appender to be reopened before the worker thread writes again.
21
+ def ask
22
+ @asked << true
23
+ end
24
+
25
+ # Returns [true|false] whether a reopen has been asked for and the worker thread has not yet
26
+ # finished it, including one that it is running. Reads only a Queue and a flag, so that it can
27
+ # be called from any thread, or a signal trap. Reads them in the opposite order to the worker
28
+ # thread, which marks the reopen as running before it takes the request, so that a reopen
29
+ # starting between the two reads is still seen.
30
+ def pending? = !@asked.empty? || @reopening
31
+
32
+ # Reopen the appender, if asked to since it was last reopened. Called by the worker thread,
33
+ # between writes. A reopen that fails is reported rather than raised, whatever the exception,
34
+ # as Appenders#reopen reports it, so that one that is not a StandardError, such as a LoadError
35
+ # or NotImplementedError, does not stop the worker thread for good: the appender keeps what it
36
+ # had, and writing to it then fails, or not, as it would have.
37
+ #
38
+ # Returns nil, or the SystemStackError when reopening overflowed the stack, so that the worker
39
+ # thread hands over to a new one, since it must not overflow its stack again: on macOS a second
40
+ # stack overflow on the same thread crashes Ruby.
41
+ def reopen_if_asked
42
+ return if @asked.empty?
43
+
44
+ @reopening = true
45
+ @asked.clear
46
+ @appender.reopen if @appender.respond_to?(:reopen)
47
+ nil
48
+ rescue Exception => e
49
+ @reporter.log(:error, "Async: Failed to reopen the appender", e)
50
+ e if e.is_a?(SystemStackError)
51
+ ensure
52
+ @reopening = false
53
+ end
54
+ end
55
+ end
56
+ end