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
@@ -25,6 +25,7 @@ module SemanticLogger
25
25
  autoload :SplunkHttp, "semantic_logger/appender/splunk_http"
26
26
  autoload :Syslog, "semantic_logger/appender/syslog"
27
27
  autoload :Tcp, "semantic_logger/appender/tcp"
28
+ autoload :TextOutput, "semantic_logger/appender/text_output"
28
29
  autoload :Udp, "semantic_logger/appender/udp"
29
30
  autoload :Wrapper, "semantic_logger/appender/wrapper"
30
31
  autoload :SentryRuby, "semantic_logger/appender/sentry_ruby"
@@ -32,6 +33,10 @@ module SemanticLogger
32
33
  # @formatter:on
33
34
 
34
35
  # Returns [SemanticLogger::Subscriber] appender for the supplied options
36
+ #
37
+ # Raises ArgumentError when the appender is to be batched, with `batch: true` or by default, see
38
+ # Subscriber#batch_by_default?, and it says why it cannot be, see Subscriber#batch_refusal. When it fails
39
+ # after .build, it first closes the appender that .build says it created, see .close_created.
35
40
  def self.factory(async: false, batch: nil,
36
41
  max_queue_size: 10_000, lag_check_interval: 1_000, lag_threshold_s: 30,
37
42
  batch_size: 300, batch_seconds: 5,
@@ -39,13 +44,16 @@ module SemanticLogger
39
44
  async_max_retries: 100,
40
45
  **args,
41
46
  &)
42
- appender = build(**args, &)
47
+ appender, created = build(**args, &)
43
48
 
44
49
  # If appender implements #batch, then it should use the batch proxy by default,
45
50
  # unless the appender opts out of batching by default (e.g. the HTTP appender).
46
51
  batch = true if batch.nil? && appender.respond_to?(:batch) && appender.batch_by_default?
47
52
 
48
53
  if batch == true
54
+ refusal = appender.batch_refusal
55
+ raise(ArgumentError, "add_appender cannot batch #{appender.class}: #{refusal}") if refusal
56
+
49
57
  Appender::Async.new(
50
58
  appender: appender,
51
59
  batch: true,
@@ -70,21 +78,45 @@ module SemanticLogger
70
78
  else
71
79
  appender
72
80
  end
81
+ rescue Exception
82
+ close_created(appender) if created
83
+ raise
84
+ end
85
+
86
+ # Closes the appender that .build created, since .factory failed after creating it, such as when the appender
87
+ # cannot be batched, and nothing else holds it, yet it may have opened its destination, such as a connection.
88
+ # An error from closing it is ignored, so that .factory raises the one that it failed with.
89
+ def self.close_created(appender)
90
+ appender.close
91
+ rescue StandardError
92
+ nil
73
93
  end
94
+ private_class_method :close_created
74
95
 
75
- # Returns [Subscriber] instance from the supplied options.
96
+ # Returns [Subscriber, true | false] the appender for the supplied options, and whether .build created both it
97
+ # and its destination, so that nothing else holds them, and .factory closes it when it fails afterwards (see
98
+ # .close_created): true for the appender for `file_name:`, or one named by a Symbol as `appender:` or `metric:`.
99
+ # False for a Subscriber instance that the caller supplied as `appender:` or `metric:`, and for the appender that
100
+ # writes to the caller's own `io:` or `logger:`: closing the one for `logger:` closes that logger, and the stream
101
+ # it writes to, such as $stdout.
102
+ #
103
+ # It adds one destination, the first of file_name:, io:, logger:, appender:, and metric: that is given, in that
104
+ # order, and ignores any other, see .report_ignored_destinations.
76
105
  def self.build(io: nil, file_name: nil, appender: nil, metric: nil, logger: nil, **args, &)
106
+ # Named in the order of the if / elsif chain below, which adds the first one given: keep the two in step.
107
+ report_ignored_destinations(file_name: file_name, io: io, logger: logger, appender: appender, metric: metric)
108
+
77
109
  if file_name
78
- SemanticLogger::Appender::File.new(file_name, **args, &)
110
+ [SemanticLogger::Appender::File.new(file_name, **args, &), true]
79
111
  elsif io
80
- SemanticLogger::Appender::IO.new(io, **args, &)
112
+ [SemanticLogger::Appender::IO.new(io, **args, &), false]
81
113
  elsif logger
82
- SemanticLogger::Appender::Wrapper.new(logger: logger, **args, &)
114
+ [SemanticLogger::Appender::Wrapper.new(logger: logger, **args, &), false]
83
115
  elsif appender
84
116
  if appender.is_a?(Symbol)
85
- SemanticLogger::Utils.constantize_symbol(appender).new(**args)
117
+ [SemanticLogger::Utils.constantize_symbol(appender).new(**args, &), true]
86
118
  elsif appender.is_a?(Subscriber)
87
- appender
119
+ [subscriber_instance(:appender, appender, **args, &), false]
88
120
  else
89
121
  raise(ArgumentError,
90
122
  "Parameter :appender must be either a Symbol or an object derived from " \
@@ -92,13 +124,13 @@ module SemanticLogger
92
124
  end
93
125
  elsif metric
94
126
  if metric.is_a?(Symbol)
95
- SemanticLogger::Utils.constantize_symbol(metric, "SemanticLogger::Metric").new(**args)
127
+ [SemanticLogger::Utils.constantize_symbol(metric, "SemanticLogger::Metric").new(**args, &), true]
96
128
  elsif metric.is_a?(Subscriber)
97
- metric
129
+ [subscriber_instance(:metric, metric, **args, &), false]
98
130
  else
99
131
  raise(ArgumentError,
100
132
  "Parameter :metric must be either a Symbol or an object derived from " \
101
- "SemanticLogger::Subscriber, not: #{appender.inspect}")
133
+ "SemanticLogger::Subscriber, not: #{metric.inspect}")
102
134
  end
103
135
  else
104
136
  raise(ArgumentError,
@@ -108,5 +140,78 @@ module SemanticLogger
108
140
  end
109
141
 
110
142
  private_class_method :build
143
+
144
+ # Returns [SemanticLogger::Base] the supplied logger, ready to be an internal logger: the one that
145
+ # Semantic Logger reports its own problems to (see Processor.logger=).
146
+ #
147
+ # An internal logger is named after whatever reports to it, logs at :trace, and takes an
148
+ # exception after the message, as every Semantic Logger appender does. So an appender, such as the
149
+ # default IO appender, or any other logger that logs at :trace, is returned as it is. Any other
150
+ # logger, such as a Ruby or Rails Logger, does none of that, so it is wrapped in a Wrapper
151
+ # appender, which writes each report to it as text, with the exception. Its own level then decides
152
+ # which reports it writes, apart from the :trace reports, which are below its lowest level, :debug,
153
+ # so are left out.
154
+ #
155
+ # Returns nil for nil or false, which restores the default internal logger.
156
+ #
157
+ # Raises ArgumentError for a SemanticLogger::Logger: it logs back into the processor, so the
158
+ # report of an appender that fails would go to that appender, fail again, and be reported again.
159
+ def self.internal_logger(logger)
160
+ return unless logger
161
+
162
+ if logger.is_a?(SemanticLogger::Logger)
163
+ raise(ArgumentError,
164
+ "A SemanticLogger::Logger cannot be the internal logger, since its reports of a failing " \
165
+ "appender would be logged to that appender. Use an appender, such as " \
166
+ "SemanticLogger::Appender::IO.new($stderr), or a Ruby Logger.")
167
+ end
168
+ return logger if logger.respond_to?(:trace)
169
+
170
+ SemanticLogger::Appender::Wrapper.new(logger: logger, level: :debug)
171
+ end
172
+
173
+ # Returns [Subscriber] the appender or metric subscriber supplied as an instance, with the `option` that named it,
174
+ # `:appender` or `:metric`, as it is, since it was created with its own options. The options and block that .build
175
+ # would hand to an appender that it creates are not used, so reports a deprecation warning that names each one,
176
+ # since v6 raises ArgumentError for them. An option whose value is nil, the default of a Subscriber, sets nothing,
177
+ # so it is not reported, and v6 must not raise for it either, so that a caller can pass on its optional settings.
178
+ # Since an option of .factory that is misspelled arrives here too, the warning names the options that do apply to
179
+ # an instance. Remove in v6, raising ArgumentError in its place.
180
+ def self.subscriber_instance(option, subscriber, **args)
181
+ ignored = args.compact.keys.map { |key| "#{key}:" }
182
+ ignored.unshift("the formatter block") if block_given?
183
+ return subscriber if ignored.empty?
184
+
185
+ pronoun = ignored.one? ? "it" : "them"
186
+ Deprecation.warn(
187
+ "add_appender ignores #{word_list(ignored)} when #{option}: is a Subscriber instance (#{subscriber.class}), " \
188
+ "and v6 raises ArgumentError for #{pronoun}. Set #{pronoun} on the instance itself; " \
189
+ "only async:, batch:, and the queue options of add_appender apply to an instance."
190
+ )
191
+ subscriber
192
+ end
193
+ private_class_method :subscriber_instance
194
+
195
+ # Reports a deprecation warning when .build is given more than one of the destinations, in the order in which it
196
+ # takes the first one, naming the one that it uses and the others, which it ignores, since v6 raises ArgumentError
197
+ # for them. A destination given as nil, or false, is not one, as .build has always taken it, so that a caller can
198
+ # pass on settings of which only one is set, such as `file_name: options[:file_name], io: options[:io]`, and v6
199
+ # must not raise for it either. Remove in v6, raising ArgumentError in its place.
200
+ def self.report_ignored_destinations(**destinations)
201
+ used, *ignored = destinations.filter_map { |name, value| "#{name}:" if value }
202
+ return if ignored.empty?
203
+
204
+ Deprecation.warn(
205
+ "add_appender adds one destination, so it uses #{used} and ignores #{word_list(ignored)}, " \
206
+ "and v6 raises ArgumentError when given more than one. Call add_appender once for each destination."
207
+ )
208
+ end
209
+ private_class_method :report_ignored_destinations
210
+
211
+ # Returns [String] the words as a list in a sentence, such as "a", "a and b", or "a, b, and c".
212
+ def self.word_list(words)
213
+ words.size < 3 ? words.join(" and ") : "#{words[0..-2].join(', ')}, and #{words.last}"
214
+ end
215
+ private_class_method :word_list
111
216
  end
112
217
  end
@@ -1,11 +1,26 @@
1
1
  module SemanticLogger
2
2
  # Manage a collection of appenders.
3
+ #
4
+ # While the process exits, it also knows which of its appenders it skips: those without a queue of
5
+ # their own whose destination failed meanwhile, and how many log messages each has not been given
6
+ # since (see #process_exiting=).
3
7
  class Appenders < Concurrent::Array
8
+ # An appender skipped while the process exits: the error with which its destination failed, and
9
+ # the number of log messages it has not been given since it was last reported.
10
+ Skipped = Struct.new(:exception, :discarded)
11
+ private_constant :Skipped
12
+
13
+ # No appender is skipped while the process is not exiting.
14
+ NONE_SKIPPED = {}.freeze
15
+ private_constant :NONE_SKIPPED
16
+
4
17
  attr_accessor :logger
5
18
 
6
19
  def initialize(logger = Processor.logger.dup)
7
20
  @logger = logger
8
21
  @logger.name = self.class.name
22
+ @exiting = false
23
+ @skipped = {}.compare_by_identity
9
24
  super()
10
25
  end
11
26
 
@@ -37,7 +52,7 @@ module SemanticLogger
37
52
  # Returns [Array<Hash>] operational statistics for each appender.
38
53
  #
39
54
  # Appenders that run asynchronously (see SemanticLogger::Appender::Async#stats) report
40
- # their queue size and processed/dropped counts. Appenders that log inline on the
55
+ # their queue size and processed/dropped/failed counts. Appenders that log inline on the
41
56
  # processor thread report only their name with `async: false`.
42
57
  def stats
43
58
  map do |appender|
@@ -49,16 +64,46 @@ module SemanticLogger
49
64
  end
50
65
  end
51
66
 
67
+ # Write the log message to every appender that should log it. An appender that fails is
68
+ # reported, and the others still write the message.
69
+ #
70
+ # While the process exits, an appender without a queue of its own is skipped once its
71
+ # destination has failed, and the message counted as not given to it (see #process_exiting=).
72
+ #
73
+ # The values of the sensitive keys are first replaced, once, so that no appender writes them
74
+ # (see SemanticLogger.sensitive_keys=).
75
+ #
76
+ # A stack overflow is not a failure of the appender but of the thread, which must not overflow
77
+ # again: on macOS a second stack overflow on the same thread crashes Ruby. It is raised to the
78
+ # processor running this thread instead, and the message goes to no further appenders.
52
79
  def log(log)
80
+ redactor = SemanticLogger.redactor
81
+ log.redact(redactor) if redactor
82
+ skipped = skipped_appenders
53
83
  each do |appender|
54
- appender.log(log) if appender.should_log?(log)
84
+ writing = appender.should_log?(log)
85
+ next unless writing
86
+ next skipped[appender].discarded += 1 if skipped.key?(appender)
87
+
88
+ appender.log(log)
89
+ rescue SystemStackError
90
+ raise
55
91
  rescue Exception => e
56
92
  logger.error "Failed to log to appender: #{appender.name}", e
93
+ skip_while_exiting(appender, e) if writing
57
94
  end
58
95
  end
59
96
 
97
+ # Flush every appender. An appender that fails is reported, and the others are still flushed.
98
+ #
99
+ # While the process exits, an appender that is skipped (see #process_exiting=) is first reported,
100
+ # with the number of log messages it has not been given since it was last reported, then flushed
101
+ # too, so that it delivers the messages it already accepted, such as those that the producer of a
102
+ # :kafka appender holds.
60
103
  def flush
104
+ skipped = skipped_appenders
61
105
  each do |appender|
106
+ report_skipped(appender, skipped[appender]) if skipped.key?(appender)
62
107
  logger.trace "Flushing appender: #{appender.name}"
63
108
  appender.flush
64
109
  rescue Exception => e
@@ -67,6 +112,13 @@ module SemanticLogger
67
112
  logger.trace "All appenders flushed"
68
113
  end
69
114
 
115
+ # Flush and close every appender, then remove those closed. An appender that fails is reported,
116
+ # and the others are still closed.
117
+ #
118
+ # A stack overflow is raised at once, as #log raises it, since the thread must not carry on: on
119
+ # macOS a second stack overflow on the same thread crashes Ruby. The appenders already closed are
120
+ # still removed. The one that overflowed the stack, and those after it, not yet closed, stay
121
+ # listed, as one whose close fails does.
70
122
  def close
71
123
  closed_appenders = []
72
124
  each do |appender|
@@ -74,15 +126,21 @@ module SemanticLogger
74
126
  appender.flush
75
127
  appender.close
76
128
  closed_appenders << appender
129
+ rescue SystemStackError
130
+ raise
77
131
  rescue Exception => e
78
132
  logger.error "Failed to close appender: #{appender.name}", e
79
133
  end
80
- # Delete appenders outside the #each above which prevents changes during iteration.
81
- closed_appenders.each { |appender| delete(appender) }
82
134
  logger.trace "All appenders closed and removed from appender list"
135
+ ensure
136
+ # Delete appenders outside the #each above which prevents changes during iteration.
137
+ closed_appenders&.each { |appender| delete(appender) }
83
138
  end
84
139
 
85
- # After a fork reopen each appender.
140
+ # After a fork, or a log rotation, reopen each appender. Called on the thread that writes to the
141
+ # appenders: the worker thread of the main Processor, or the calling thread with sync!. An
142
+ # appender added with async: true or in batches is asked to reopen, by its own worker thread
143
+ # (see Appender::Async#reopen).
86
144
  def reopen
87
145
  each do |appender|
88
146
  next unless appender.respond_to?(:reopen)
@@ -94,5 +152,87 @@ module SemanticLogger
94
152
  end
95
153
  logger.trace "All appenders re-opened"
96
154
  end
155
+
156
+ # Tell each appender added with async: true or in batches whether the process is exiting: true
157
+ # before the flush at exit, and false once it has returned (see QueueProcessor#process_exiting=).
158
+ # Each one's queue processor is told straight away, rather than through the queue of the thread
159
+ # that writes to every appender, which can be held up handing an entry to the full queue of an
160
+ # appender whose worker thread is backing off during an outage. Takes no lock, so that it can be
161
+ # called from any thread, or a signal trap. An appender that raises is reported, as for #flush,
162
+ # and the others are still told, so that the flush at exit still runs.
163
+ #
164
+ # The appenders without a queue of their own are written to here, one log message after another,
165
+ # by the thread that writes to every appender, so that during an outage the flush at exit would
166
+ # wait while each message queued ahead of it failed in turn, up to a timeout each against a
167
+ # server that does not answer. So while the process exits, once the destination of such an
168
+ # appender fails, other than for the content of a message (see Subscriber#message_error?), it is
169
+ # skipped until the process no longer exits: #log gives it no more messages, counting them, and
170
+ # #flush reports them, then still flushes it, so that it delivers what it already accepted. The
171
+ # other appenders are still given every message.
172
+ #
173
+ # It applies only in the process that exits, not in a child process forked meanwhile.
174
+ def process_exiting=(exiting)
175
+ @skipped = {}.compare_by_identity if exiting
176
+ @exiting = exiting && ::Process.pid
177
+ each do |appender|
178
+ appender.process_exiting = exiting if appender.respond_to?(:process_exiting=)
179
+ rescue Exception => e
180
+ logger.error "Failed to tell appender that the process is exiting: #{appender.name}", e
181
+ end
182
+ end
183
+
184
+ # After a fork, replace the queue and worker thread of each appender added with async: true or
185
+ # in batches with the child's own, on the calling thread (see QueueProcessor#renew_after_fork).
186
+ # Takes no lock, so that it can be called from a signal trap.
187
+ def renew_after_fork
188
+ each { |appender| appender.renew_after_fork if appender.respond_to?(:renew_after_fork) }
189
+ end
190
+
191
+ # Returns [true|false] whether the thread is the worker thread of one of the appenders: one added
192
+ # with async: true or in batches, which writes to it (see QueueProcessor#worker_thread?). The thread
193
+ # that writes to every appender may be waiting for it, so it must not wait for that thread. Takes
194
+ # no lock, so that it can be called from a signal trap.
195
+ def worker_thread?(thread = Thread.current)
196
+ any? { |appender| appender.respond_to?(:worker_thread?) && appender.worker_thread?(thread) }
197
+ end
198
+
199
+ # Returns [true|false] whether the thread is the worker thread of one of the appenders while that
200
+ # appender's queue is full, or a flush or close of it is waiting (see QueueProcessor#holding_up?):
201
+ # the thread that writes to every appender may then be waiting for it, to make room or to run that
202
+ # request. Takes no lock, as #worker_thread? takes none.
203
+ def holding_up?(thread = Thread.current)
204
+ any? { |appender| appender.respond_to?(:holding_up?) && appender.holding_up?(thread) }
205
+ end
206
+
207
+ private
208
+
209
+ # Whether this process is exiting (see #process_exiting=), rather than a child process forked while
210
+ # it was.
211
+ def exiting? = @exiting && @exiting == ::Process.pid
212
+
213
+ # Returns [Hash] the appenders skipped while the process exits, by appender, or none while it does
214
+ # not. The process can stop exiting while the thread that writes to every appender fails to write
215
+ # to one, so one skipped then is left out until the process exits again, which starts afresh.
216
+ def skipped_appenders = exiting? ? @skipped : NONE_SKIPPED
217
+
218
+ # While the process exits, skip an appender without a queue of its own once writing to it failed
219
+ # because of its destination (see #process_exiting=). An appender with a queue of its own is told
220
+ # that the process is exiting, and handles it itself.
221
+ def skip_while_exiting(appender, exception)
222
+ return unless exiting?
223
+ return if appender.respond_to?(:process_exiting=)
224
+ return if appender.respond_to?(:message_error?) && appender.message_error?(exception)
225
+
226
+ @skipped[appender] = Skipped.new(exception, 0)
227
+ end
228
+
229
+ # Report the log messages that a skipped appender has not been given since it was last reported.
230
+ def report_skipped(appender, skipped)
231
+ return if skipped.discarded.zero?
232
+
233
+ logger.error "Discarded #{skipped.discarded} log message(s) during the flush at exit, after the " \
234
+ "destination failed, for appender: #{appender.name}", skipped.exception
235
+ skipped.discarded = 0
236
+ end
97
237
  end
98
238
  end
@@ -0,0 +1,77 @@
1
+ module SemanticLogger
2
+ # Asks an application's backtrace cleaner, such as `Rails.backtrace_cleaner`, to clean a backtrace.
3
+ #
4
+ # A backtrace cleaner is any object that responds to `#clean`, as ActiveSupport::BacktraceCleaner
5
+ # does, or to `#call`, such as a Proc. It is given the backtrace as an Array of Strings, and
6
+ # returns the lines to log in its place: it can leave lines out, and shorten or rewrite them.
7
+ #
8
+ # Internal: Log caches the result for each of its exceptions; see Log#backtrace_of.
9
+ module BacktraceCleaning
10
+ # Returns [true|false] whether the object can clean a backtrace.
11
+ def self.cleaner?(object)
12
+ object.respond_to?(:clean) || object.respond_to?(:call)
13
+ end
14
+
15
+ # Returns the cleaner, for a setting that holds one.
16
+ # Raises ArgumentError when it cannot clean a backtrace (see .cleaner?), naming what the
17
+ # setting expects, since it can accept other values too.
18
+ def self.validate!(cleaner, expected: "a backtrace cleaner")
19
+ return cleaner if cleaner?(cleaner)
20
+
21
+ raise(ArgumentError, "Expected #{expected} that responds to #clean or #call, not #{cleaner.inspect}")
22
+ end
23
+
24
+ # Returns [Array<String>] the backtrace as the cleaner cleans it, or nil when there is none.
25
+ # The Array and its lines are frozen copies, so that every appender can share them.
26
+ #
27
+ # Returns a copy of the supplied backtrace instead when the cleaner leaves out every line, so
28
+ # that the only clue to where an exception came from is never lost, for example an exception
29
+ # raised entirely within gems that a cleaner silences. Also when the cleaner does not return an
30
+ # Array of lines, or raises a StandardError, such as for an object that is not a cleaner, so
31
+ # that a cleaner cannot stop a log entry being written. The error is reported to the internal
32
+ # logger, since nothing else would show that the cleaner is broken.
33
+ #
34
+ # The cleaner is given a copy of the backtrace, which it may change, since the supplied one
35
+ # belongs to the exception, and other appenders, such as error services, also read it.
36
+ def self.clean(backtrace, cleaner)
37
+ return if backtrace.nil?
38
+
39
+ cleaned_lines(backtrace, cleaner) || frozen_copy(backtrace)
40
+ end
41
+
42
+ # Returns [Array<String>] a frozen copy of the lines the cleaner keeps, or nil when it keeps
43
+ # none, does not return an Array of lines, or raises.
44
+ def self.cleaned_lines(backtrace, cleaner)
45
+ return if backtrace.empty?
46
+
47
+ lines = backtrace.dup
48
+ cleaned = cleaner.respond_to?(:clean) ? cleaner.clean(lines) : cleaner.call(lines)
49
+ frozen_copy(cleaned) if cleaned.is_a?(Array) && !cleaned.empty?
50
+ rescue StandardError => e
51
+ report(e)
52
+ nil
53
+ end
54
+ private_class_method :cleaned_lines
55
+
56
+ # Returns [Array<String>] a frozen copy of the lines, each a frozen copy too, which leaves the
57
+ # supplied lines, such as the exception's own, unchanged. A cleaner can return
58
+ # Thread::Backtrace::Location objects, or Strings of its own.
59
+ def self.frozen_copy(lines)
60
+ lines.map { |line| String.new(line.to_s).freeze }.freeze
61
+ end
62
+ private_class_method :frozen_copy
63
+
64
+ # Reports an error raised by a cleaner to the internal logger, as text: given the exception
65
+ # itself, the internal logger's formatter would ask the same cleaner to clean its backtrace.
66
+ def self.report(exception)
67
+ where = exception.backtrace&.first
68
+ Logger.processor.logger.warn(
69
+ "Backtrace cleaner raised #{Utils.exception_name(exception)}: #{Utils.exception_message(exception)}" \
70
+ "#{" (#{where})" if where}, so the full backtrace is logged"
71
+ )
72
+ rescue StandardError
73
+ nil
74
+ end
75
+ private_class_method :report
76
+ end
77
+ end