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
@@ -8,7 +8,8 @@ module SemanticLogger
8
8
  # :trace, :debug, :info, :warn, :error, :fatal
9
9
  #
10
10
  # thread_name
11
- # Name of the thread in which the logging call was called
11
+ # Name of the thread in which the logging call was called,
12
+ # or its object id when the thread has no name
12
13
  #
13
14
  # name
14
15
  # Class name supplied to the logging instance
@@ -40,31 +41,80 @@ module SemanticLogger
40
41
  # backtrace [Array<String>]
41
42
  # The backtrace captured at source when the log level >= SemanticLogger.backtrace_level
42
43
  #
44
+ # call_site [CallSite]
45
+ # Where the entry was logged: the path, line, and label (usually the method) of the code that
46
+ # made the log call, when the log level >= SemanticLogger.call_site_level. The one the log call
47
+ # supplies as `call_site:`, or nil for `call_site: false`, or else the first line of a backtrace
48
+ # it supplies. nil below that level.
49
+ #
43
50
  # metric_amount [Numeric]
44
51
  # Used for numeric or counter metrics.
45
52
  # For example, the number of inquiries or, the amount purchased etc.
46
53
  #
47
54
  # context [Hash]
48
55
  # Named contexts that were captured when the log entry was created.
56
+ #
57
+ # captures [Hash]
58
+ # Objects that an appender captured on the logging thread for its own use when the log entry
59
+ # was created, such as the OpenTelemetry context. Only a formatter built for that appender writes
60
+ # them, as the NewRelicLogs formatter writes the linking metadata its appender captures.
61
+ #
62
+ # The payload, named tags, context, and dimensions have the values of sensitive keys replaced
63
+ # before the entry is written to any appender, when SemanticLogger.sensitive_keys is set (see
64
+ # #redact).
49
65
  class Log
50
66
  # Keys passed in without a payload that will be extracted and the remainder passed into the payload.
51
- NON_PAYLOAD_KEYS = %i[message exception backtrace exception
52
- duration min_duration
53
- log_exception on_exception_level
54
- metric metric_amount dimensions].freeze
67
+ NON_PAYLOAD_KEYS = %i[message exception backtrace call_site duration min_duration
68
+ log_exception on_exception_level metric metric_amount dimensions].freeze
69
+
70
+ # Values accepted for the :log_exception argument.
71
+ LOG_EXCEPTION_OPTIONS = %i[full partial none].freeze
72
+ private_constant :LOG_EXCEPTION_OPTIONS
73
+
74
+ # A finite real number, which #assign can compare with another one.
75
+ REAL_NUMBER = Utils.make_shareable(->(value) { value.is_a?(Numeric) && value.real? && value.finite? })
76
+ private_constant :REAL_NUMBER
77
+
78
+ # Checks that a value is valid for its argument, for the arguments that do not accept any value.
79
+ # Any other value would make #assign, or the formatters, raise.
80
+ ARGUMENT_VALIDATORS = Utils.make_shareable(
81
+ {
82
+ backtrace: ->(value) { value.is_a?(Array) && value.all?(String) },
83
+ call_site: ->(value) { CallSite.supplied?(value) },
84
+ duration: REAL_NUMBER,
85
+ min_duration: REAL_NUMBER,
86
+ metric_amount: REAL_NUMBER,
87
+ dimensions: ->(value) { value.is_a?(Hash) },
88
+ log_exception: ->(value) { LOG_EXCEPTION_OPTIONS.include?(value) },
89
+ on_exception_level: ->(value) { Levels.valid?(value) }
90
+ }.freeze
91
+ )
92
+ private_constant :ARGUMENT_VALIDATORS
93
+
94
+ # Hash#key?, which unlike HashWithIndifferentAccess#key? only matches the exact Symbol key.
95
+ HASH_KEY = Utils.make_shareable(Hash.instance_method(:key?))
96
+ private_constant :HASH_KEY
97
+
98
+ # Returns [String] the name that identifies the thread in a log entry: the thread's own name,
99
+ # or its object id when it has none, which Ruby never reuses within a process.
100
+ def self.thread_name_for(thread) = thread.name || thread.object_id.to_s
55
101
 
56
102
  attr_accessor :level, :level_index, :name, :message, :time, :duration,
57
- :payload, :exception, :thread_name, :backtrace,
58
- :tags, :named_tags, :context,
103
+ :payload, :exception, :thread_name, :backtrace, :call_site,
104
+ :tags, :named_tags, :context, :captures,
59
105
  :metric, :metric_amount, :dimensions
60
106
 
61
- def initialize(name, level, index = nil)
107
+ # Parameters
108
+ # thread: [Thread]
109
+ # The thread whose name, tags, and named tags the entry has.
110
+ # Default: Thread.current
111
+ def initialize(name, level, index = nil, thread = Thread.current)
62
112
  @level = level
63
- @thread_name = Thread.current.name
113
+ @thread_name = Log.thread_name_for(thread)
64
114
  @name = name
65
115
  @time = Time.now
66
- @tags = SemanticLogger.tags
67
- @named_tags = SemanticLogger.named_tags
116
+ @tags = Context.tags(thread)
117
+ @named_tags = Context.named_tags(thread)
68
118
  @level_index = index.nil? ? Levels.index(level) : index
69
119
  end
70
120
 
@@ -82,6 +132,7 @@ module SemanticLogger
82
132
  metric_amount: nil,
83
133
  duration: nil,
84
134
  backtrace: nil,
135
+ call_site: nil,
85
136
  log_exception: :full,
86
137
  on_exception_level: nil,
87
138
  dimensions: nil)
@@ -91,10 +142,11 @@ module SemanticLogger
91
142
  self.metric = metric
92
143
  self.metric_amount = metric_amount
93
144
  self.dimensions = dimensions
145
+ Log.negative_metric_amount_deprecated if counted_negative_amount?
94
146
 
95
147
  if exception
96
148
  unless exception.is_a?(Exception)
97
- exception = ArgumentError.new("Invalid value for logger exception: #{exception.inspect}")
149
+ exception = ArgumentError.new("Invalid value for logger exception: #{Utils.safe_inspect(exception)}")
98
150
  exception.set_backtrace(Utils.extract_backtrace(caller))
99
151
  end
100
152
 
@@ -102,7 +154,10 @@ module SemanticLogger
102
154
  when :full
103
155
  self.exception = exception
104
156
  when :partial
105
- self.message = "#{message} -- Exception: #{exception.class}: #{exception.message}"
157
+ # The class and message of the exception, then of each exception that caused it: the same
158
+ # exceptions that :full writes (see #backtrace_to_s).
159
+ self.message = with_class(" -- Exception: ", exception, ": ", message_of(exception))
160
+ each_exception(exception) { |ex, depth| self.message = with_cause(ex) unless depth.zero? }
106
161
  when nil, :none
107
162
  # Log the message without the exception that was raised
108
163
  nil
@@ -111,8 +166,10 @@ module SemanticLogger
111
166
  end
112
167
  # On exception change the log level
113
168
  if on_exception_level
114
- self.level = on_exception_level
115
- self.level_index = Levels.index(level)
169
+ # Normalized through the index, so that a level supplied as a String or an Integer is
170
+ # still stored as its Symbol.
171
+ self.level_index = Levels.index(on_exception_level)
172
+ self.level = Levels.level(level_index)
116
173
  end
117
174
  end
118
175
 
@@ -121,72 +178,136 @@ module SemanticLogger
121
178
  return false if duration && (duration < min_duration) && exception.nil?
122
179
 
123
180
  if backtrace
124
- self.backtrace = Utils.extract_backtrace(backtrace)
181
+ backtrace = self.backtrace = Utils.extract_backtrace(backtrace)
125
182
  elsif level_index >= SemanticLogger.backtrace_level_index
126
183
  self.backtrace = Utils.extract_backtrace(caller)
127
184
  end
128
185
 
186
+ # A call site or backtrace supplied by the log call says where the entry is about, such as the
187
+ # application code that ran a query, or the thread whose backtrace is logged.
188
+ if level_index >= SemanticLogger.call_site_level_index
189
+ self.call_site = CallSite.locate(call_site: call_site, backtrace: backtrace)
190
+ end
191
+
129
192
  true
130
193
  end
131
194
 
132
- # Keys that #assign_hash may assign directly to a log attribute. Every other
133
- # key is folded into the payload, preventing a supplied hash from overwriting
134
- # sensitive fields such as :level, :name, or :time, and keeping this path
135
- # consistent with #extract_arguments.
136
- ASSIGNABLE_KEYS = (NON_PAYLOAD_KEYS + %i[payload]).freeze
195
+ # Log attributes that a Hash returned by a logging block can set (see #assign_hash). Its other
196
+ # keys go to the payload, so that it cannot set fields such as :level, :name, or :time.
197
+ ASSIGNABLE_KEYS = %i[message exception backtrace duration metric metric_amount dimensions].freeze
137
198
 
138
- # Assign known keys to self, all other keys to the payload.
199
+ # Assign the Hash returned by a logging block, after #assign has applied the log call.
200
+ #
201
+ # A block can return untrusted data, such as a parsed request body, so its keys are classified
202
+ # by #extract_arguments, as for a Hash passed after the message. A log argument is only assigned
203
+ # when this entry does not have it yet (an exception must also be an Exception), and otherwise
204
+ # goes to the payload like any other key. Whatever the key order, the log call's values win,
205
+ # then the block's top-level keys, then those of its :payload. No supplied Hash is modified.
139
206
  def assign_hash(hash)
140
- self.payload ||= {}
141
- hash.each_pair do |key, value|
142
- if ASSIGNABLE_KEYS.include?(key) && respond_to?(:"#{key}=")
143
- public_send(:"#{key}=", value)
144
- else
145
- payload[key] = value
146
- end
147
- end
148
- self.payload = nil if payload.empty?
207
+ args = extract_arguments(hash)
208
+ added = args.delete(:payload)
209
+ assigned, kept = args.partition { |key, value| block_attribute?(key, value) }
210
+ assigned.each { |key, value| public_send(:"#{key}=", value) }
211
+ # Once per process, so that #assign having reported it already does no harm.
212
+ Log.negative_metric_amount_deprecated if counted_negative_amount?
213
+ # An argument this entry already has wins over the block's :payload, like the block's other keys.
214
+ added = merge_payload(kept.to_h, added) unless kept.empty?
215
+ self.payload = merge_payload(payload, added)
149
216
  self
150
217
  end
151
218
 
219
+ # Reports, once per process, that a log call gave a negative metric amount, which is deprecated:
220
+ # a metric counts upward, and v6 drops a negative amount. The entry is still logged with it.
221
+ #
222
+ # Only once, so that a negative amount in a loop does not report a warning for each log call, and
223
+ # only once deprecation warnings are on, so that turning them on later still reports it. Not from
224
+ # a Ractor other than the main one, which cannot record that it was reported. Two threads that
225
+ # report at the same moment can each report it, which costs a second warning at worst. Remove in
226
+ # v6, where the metrics API drops a negative amount instead.
227
+ #
228
+ # Internal: called by #assign and #assign_hash only (@api private).
229
+ def self.negative_metric_amount_deprecated
230
+ return if !Warning[:deprecated] || RactorSupport.other_ractor? || @negative_metric_amount_reported
231
+
232
+ @negative_metric_amount_reported = true
233
+ Deprecation.warn(
234
+ "A negative metric_amount is deprecated: a metric counts upward, and v6 drops a negative amount. " \
235
+ "Count what goes down as a metric of its own, such as \"cart/items_removed\". " \
236
+ "This is reported for the first negative amount only. See " \
237
+ "https://logger.reidmorrison.com/upgrading.html#negative-metric-amounts"
238
+ )
239
+ end
240
+
241
+ # Returns [true|false] whether the value can be used as the log argument named by the key.
242
+ #
243
+ # Never raises, so it can check values from untrusted data before they are passed to #assign.
244
+ # A nil value is never an argument, since it means the argument was not supplied. Arguments
245
+ # without a validator in ARGUMENT_VALIDATORS (such as :message, :metric, or :exception, which
246
+ # #assign logs as an ArgumentError when it is not an Exception) accept any other value.
247
+ def self.argument?(key, value)
248
+ return false if value.nil? || !NON_PAYLOAD_KEYS.include?(key)
249
+
250
+ validator = ARGUMENT_VALIDATORS[key]
251
+ validator.nil? || validator.call(value)
252
+ end
253
+
152
254
  # Extract the arguments from a Hash Payload
255
+ #
256
+ # The hash can hold untrusted data, so this never fails because of its content: keys that are
257
+ # not log attributes, or that hold a value that is not valid for it (see .argument?), are kept
258
+ # in the payload. A log attribute key with a nil value counts as not supplied, so #assign uses
259
+ # its default. When the hash supplies an explicit :payload, any other keys are merged into it,
260
+ # and win over its values of the same name, since the explicit payload is where untrusted data
261
+ # goes (see docs/security.md).
153
262
  def extract_arguments(payload, message = nil)
154
263
  raise(ArgumentError, "payload must be a Hash") unless payload.is_a?(Hash)
155
264
 
156
- message = nil if message == ""
157
- if payload.key?(:payload)
158
- return message ? payload.merge(message: message) : payload
159
- end
160
-
265
+ message = nil if message == ""
266
+ explicit = HASH_KEY.bind_call(payload, :payload)
161
267
  new_payload = {}
162
268
  args = {}
163
269
  payload.each_pair do |key, value|
164
- # Supplied message takes precedence
165
- if (key == :message) && !message.nil?
166
- new_payload[key] = value
270
+ if explicit && key == :payload
271
+ args[:payload] = value
272
+ elsif key == :message && !message.nil?
273
+ # Supplied message takes precedence
274
+ new_payload[key] = value unless explicit
275
+ elsif Log.argument?(key, value)
276
+ args[key] = value
277
+ elsif value.nil? && NON_PAYLOAD_KEYS.include?(key)
278
+ # Not supplied, so #assign uses its default
167
279
  next
280
+ else
281
+ new_payload[key] = value
168
282
  end
169
-
170
- NON_PAYLOAD_KEYS.include?(key) ? args[key] = value : new_payload[key] = value
171
283
  end
172
- args[:payload] = new_payload unless new_payload.empty?
284
+ unless new_payload.empty?
285
+ args[:payload] = explicit ? merge_payload(new_payload, args[:payload]) : new_payload
286
+ end
173
287
  args[:message] = message if message
174
288
  args
175
289
  end
176
290
 
177
291
  MAX_EXCEPTIONS_TO_UNWRAP = 5
178
292
  # Call the block for exception and any nested exception
179
- def each_exception
293
+ #
294
+ # Parameters
295
+ # first: [Exception|nil]
296
+ # The exception to start from, for one that this entry does not keep, such as the one that
297
+ # log_exception: :partial writes into the message.
298
+ # Default: this entry's exception
299
+ #
300
+ # Yields each exception with its depth: 0 for the first one, 1 for the exception that caused it,
301
+ # and so on.
302
+ def each_exception(first = exception)
180
303
  # With thanks to https://github.com/bugsnag/bugsnag-ruby/blob/6348306e44323eee347896843d16c690cd7c4362/lib/bugsnag/notification.rb#L81
181
- depth = 0
182
304
  exceptions = []
183
- ex = exception
305
+ ex = first
184
306
  while !ex.nil? && !exceptions.include?(ex) && exceptions.length < MAX_EXCEPTIONS_TO_UNWRAP
185
307
  exceptions << ex
186
- yield(ex, depth)
308
+ yield(ex, exceptions.length - 1)
187
309
 
188
- depth += 1
189
- ex =
310
+ ex =
190
311
  if ex.respond_to?(:cause) && ex.cause
191
312
  ex.cause
192
313
  elsif ex.respond_to?(:continued_exception) && ex.continued_exception
@@ -197,17 +318,83 @@ module SemanticLogger
197
318
  end
198
319
  end
199
320
 
321
+ # Returns [String] the detail that Ruby's Exception#detailed_message adds to the message of the
322
+ # supplied exception, without the class name that Ruby also adds. Since Ruby 3.2 this is where
323
+ # did_you_mean suggestions ("Did you mean? upcase") and the detail an exception class supplies
324
+ # by overriding #detailed_message appear, rather than in #message.
325
+ # Returns nil when there is no detail.
326
+ #
327
+ # Parameters
328
+ # exception: [Exception]
329
+ # This entry's exception, or one of its causes (see #each_exception).
330
+ # source: [true|false]
331
+ # Whether to include error_highlight's snippet of the failing source line, for example
332
+ # "user_name.upcas" with "^^^^^^" under the unknown method. It re-parses that source
333
+ # file on every call, so it is about 100 times slower, and it copies source code into
334
+ # the log.
335
+ # Default: false
336
+ #
337
+ # The result is cached on this entry, since every appender's formatter may ask for it.
338
+ def exception_details(exception, source: false)
339
+ cached([:exception_details, exception.__id__, source]) { ExceptionDetails.extract(exception, source: source) }
340
+ end
341
+
342
+ # Returns [Array<String>] the backtrace of the supplied exception, or nil when it has none.
343
+ #
344
+ # Parameters
345
+ # exception: [Exception]
346
+ # This entry's exception, or one of its causes (see #each_exception).
347
+ # cleaner: [Object|nil]
348
+ # A backtrace cleaner, such as `Rails.backtrace_cleaner`, that responds to `#clean` or
349
+ # `#call`. The backtrace is returned as it cleans it (see BacktraceCleaning.clean), and the
350
+ # exception's own backtrace is left unchanged. Any other value, such as the `true` of the
351
+ # formatter option, is reported to the internal logger as a broken cleaner, and the full
352
+ # backtrace is returned.
353
+ # Default: nil (the exception's own backtrace)
354
+ #
355
+ # A cleaned backtrace is frozen, as are its lines, and cached on this entry, since every
356
+ # appender's formatter may ask for it. Nothing is cached while the exception has no backtrace:
357
+ # one that was never raised can be given one later, as the Bugsnag appender does.
358
+ def backtrace_of(exception, cleaner: nil)
359
+ return exception.backtrace unless cleaner && exception.backtrace
360
+
361
+ cached([:backtrace, exception.__id__, cleaner.__id__]) { BacktraceCleaning.clean(exception.backtrace, cleaner) }
362
+ end
363
+
200
364
  # Returns [String] the exception backtrace including all of the child / caused by exceptions
201
- def backtrace_to_s
202
- trace = ""
365
+ #
366
+ # When a cleaner is supplied, each backtrace is cleaned by it first (see #backtrace_of).
367
+ #
368
+ # When a block is supplied, each cause's message and each backtrace line is passed
369
+ # to it, in the order they are written, and the value it returns is written in its
370
+ # place. This lets a caller, for example a formatter, transform that text while this
371
+ # method keeps the layout.
372
+ #
373
+ # Lines are separated by a line break, with none added before the first or after the
374
+ # last, even when an exception in the chain has no backtrace, so that a caller can put
375
+ # the text on the line after its own.
376
+ #
377
+ # Never raises because of what it writes: each cause is named as Utils.exception_name names it,
378
+ # as Ruby names its class, without asking the class, such as `#<Class:0x000...>` for an anonymous
379
+ # class, which has no name; its message is read as Utils.exception_message reads it, so
380
+ # that a #message that raises, or does not return a String, cannot make it raise, nor pass the
381
+ # block anything but a String; and the lines are joined as Utils.join_lines joins them, whatever
382
+ # their encodings.
383
+ #
384
+ # Example:
385
+ # log.backtrace_to_s { |text| text.gsub("\n", "\\n") }
386
+ # log.backtrace_to_s(cleaner: Rails.backtrace_cleaner)
387
+ def backtrace_to_s(cleaner: nil, &block)
388
+ lines = []
203
389
  each_exception do |exception, i|
204
- if i.zero?
205
- trace = (exception.backtrace || []).join("\n")
206
- else
207
- trace << "\nCause: #{exception.class.name}: #{exception.message}\n#{(exception.backtrace || []).join("\n")}"
390
+ unless i.zero?
391
+ message = block ? yield(message_of(exception)) : message_of(exception)
392
+ lines << Utils.join_texts("Cause: ", Utils.exception_name(exception), ": ", message)
208
393
  end
394
+ backtrace = backtrace_of(exception, cleaner: cleaner) || []
395
+ lines.concat(block ? backtrace.map(&block) : backtrace)
209
396
  end
210
- trace
397
+ Utils.join_lines(lines)
211
398
  end
212
399
 
213
400
  # Returns [String] duration of the log entry as a string
@@ -244,9 +431,7 @@ module SemanticLogger
244
431
  end
245
432
 
246
433
  # Returns [String] single character upper case log level
247
- def level_to_s
248
- level.to_s[0..0].upcase
249
- end
434
+ def level_to_s = level.to_s[0..0].upcase
250
435
 
251
436
  # DEPRECATED
252
437
  def process_info(thread_name_length = 30)
@@ -256,23 +441,17 @@ module SemanticLogger
256
441
  "#{$$}:#{format("%.#{thread_name_length}s", thread_name)}#{file_name}"
257
442
  end
258
443
 
259
- CALLER_REGEXP = /^(.*):(\d+).*/
260
-
261
- # Extract the filename and line number from the last entry in the supplied backtrace
444
+ # Extract the file name and line number from the first line of the supplied backtrace.
262
445
  def extract_file_and_line(stack, short_name = false)
263
- return unless stack&.size&.positive?
264
-
265
- match = CALLER_REGEXP.match(stack.first)
266
- return unless match
267
-
268
- [short_name ? File.basename(match[1]) : match[1], match[2].to_i]
446
+ CallSite.parse(stack&.first)&.file_name_and_line(short_name: short_name)
269
447
  end
270
448
 
271
- # Returns [String, String] the file_name and line_number from the backtrace supplied
272
- # in either the backtrace or exception
449
+ # Returns [String, Integer] the file name and line number where the entry was logged: from the call
450
+ # site, or else the first line of the backtrace, or of the exception's backtrace.
451
+ # nil when there are none.
273
452
  def file_name_and_line(short_name = false)
274
- stack = backtrace || exception&.backtrace
275
- extract_file_and_line(stack, short_name)
453
+ call_site&.file_name_and_line(short_name: short_name) ||
454
+ extract_file_and_line(backtrace || exception&.backtrace, short_name)
276
455
  end
277
456
 
278
457
  # Strip the standard Rails colorizing from the logged message.
@@ -281,8 +460,13 @@ module SemanticLogger
281
460
  # terminal escape codes out of structured (JSON/Loki) output. It is distinct
282
461
  # from Formatters::Base#escape_control_characters, which instead *escapes*
283
462
  # (preserves) control characters and is opt-in for the text formatters.
463
+ #
464
+ # A message tagged UTF-8 can hold invalid bytes, for example a request parameter that Rack
465
+ # decoded from "%FF", or be in another encoding, such as a binary request body. Stripping or
466
+ # matching such a String raises, so it is converted to valid UTF-8 first, dropping the
467
+ # invalid bytes, as the JSON formatters do.
284
468
  def cleansed_message
285
- msg = message.to_s
469
+ msg = Utils.encode_utf8_string(message.to_s)
286
470
  return msg.strip unless msg.include?("\e")
287
471
 
288
472
  msg.gsub(/\e\[[\d;]*[mz]?|\e/, "").strip
@@ -290,14 +474,17 @@ module SemanticLogger
290
474
 
291
475
  # Return the payload in text form
292
476
  # Returns nil if payload is missing or empty
293
- def payload_to_s
294
- payload.inspect if payload?
295
- end
477
+ #
478
+ # Rendered with #inspect, or with the block when given (for example Amazing Print). A payload
479
+ # nested too deeply for either is first cut off at Utils::MAX_JSON_SAFE_DEPTH, rather than
480
+ # raising SystemStackError (see Utils.safe_inspect).
481
+ def payload_to_s(&) = (Utils.safe_inspect(payload, &) if payload?)
296
482
 
297
483
  # Returns [true|false] whether the log entry has a payload
298
- def payload?
299
- !(payload.nil? || (payload.respond_to?(:empty?) && payload.empty?))
300
- end
484
+ def payload? = !(payload.nil? || (payload.respond_to?(:empty?) && payload.empty?))
485
+
486
+ # Returns [true|false] whether the log entry has a metric with dimensions: a Hash that is not empty.
487
+ def dimensions? = metric ? dimensions.is_a?(Hash) && !dimensions.empty? : false
301
488
 
302
489
  def to_h(host = SemanticLogger.host, application = SemanticLogger.application,
303
490
  environment = SemanticLogger.environment)
@@ -306,13 +493,128 @@ module SemanticLogger
306
493
  end
307
494
 
308
495
  # Lazy initializes the context hash and assigns a key value pair.
309
- def set_context(key, value)
310
- (self.context ||= {})[key] = value
496
+ def set_context(key, value) = (self.context ||= {}).store(key, value)
497
+
498
+ # Keeps the value, captured on the logging thread, for the appender that uses it. Unlike the
499
+ # context, formatters do not write it, unless one is built for that appender and reads its key.
500
+ def capture(key, value) = (self.captures ||= {}).store(key, value)
501
+
502
+ # Returns the value captured with the key, or nil when there is none.
503
+ def captured(key) = captures&.[](key)
504
+
505
+ # Replaces this entry's payload, named tags, context, and metric dimensions, the fields that
506
+ # hold keyed data, with copies in which the value of every sensitive key is replaced (see
507
+ # Redactor#redact). Returns self.
508
+ #
509
+ # The values replaced are left as they are, since they can be the application's own, or be
510
+ # shared with other entries, as named tags are. A field with no sensitive key is kept as it is.
511
+ #
512
+ # Called once, before the entry is written to any appender (see SemanticLogger.sensitive_keys=).
513
+ def redact(redactor)
514
+ self.payload = redactor.redact(payload)
515
+ self.named_tags = redactor.redact(named_tags)
516
+ self.context = redactor.redact(context)
517
+ self.dimensions = redactor.redact(dimensions)
518
+ self
311
519
  end
312
520
 
313
521
  # A metric only event has a metric but no message or exception.
314
- def metric_only?
315
- metric && message.nil? && exception.nil?
522
+ def metric_only? = metric && message.nil? && exception.nil?
523
+
524
+ # Replaces the values of this entry that cannot be copied to another Ractor, such as a Proc in its
525
+ # payload (see RactorCopy). Returns self. Experimental, Ruby 4.0 and later only.
526
+ def make_copyable
527
+ %i[message payload tags named_tags context captures metric dimensions].each do |field|
528
+ public_send(:"#{field}=", RactorCopy.copyable(public_send(field)))
529
+ end
530
+ self.exception = RactorCopy.copyable_exception(exception) if exception
531
+ @cache = nil
532
+ self
533
+ end
534
+
535
+ private
536
+
537
+ # Returns [true|false] whether this entry gives a metric a negative amount, which is deprecated (see
538
+ # .negative_metric_amount_deprecated): whether it has a metric and a metric amount that is a real
539
+ # number below zero. Also for a measure_* entry, since SignalFx adds its amount to a counter too.
540
+ # Without a metric no metric subscriber receives the amount. Costs a nil check when there is no
541
+ # metric. Never raises, since Base#backtrace passes its metric_amount to #assign without checking it.
542
+ def counted_negative_amount? = metric && REAL_NUMBER.call(metric_amount) && metric_amount.negative?
543
+
544
+ # Returns the kept payload with the keys of the added one that it does not have, so that a kept
545
+ # value is never replaced. A String and a Symbol key of the same name, such as "account_id" from
546
+ # JSON.parse and :account_id, count as the same key, since the formatters write both under that
547
+ # name. A payload that is not a Hash is kept as its :payload key, but the kept payload is
548
+ # returned unchanged when there is nothing to add. Neither payload is modified.
549
+ def merge_payload(kept, added)
550
+ added = {payload: added} unless added.nil? || added.is_a?(Hash)
551
+ return kept if added.nil? || added.empty?
552
+
553
+ kept = {payload: kept} unless kept.nil? || kept.is_a?(Hash)
554
+ return added if kept.nil? || kept.empty?
555
+
556
+ merged = kept.merge(added) { |_key, kept_value, _added_value| kept_value }
557
+ # Only the kept keys, usually a few supplied by the application, are checked one at a time.
558
+ kept.each_key do |key|
559
+ next unless key.is_a?(Symbol) || key.is_a?(String)
560
+
561
+ other = key.is_a?(Symbol) ? key.name : key.to_sym
562
+ merged.delete(other) unless kept.key?(other)
563
+ end
564
+ merged
565
+ end
566
+
567
+ # Returns the value cached on this entry for the key, after caching the value the block returns
568
+ # when there is none yet. Used for values derived from the entry that every appender's formatter
569
+ # may ask for.
570
+ #
571
+ # Keys hold objects by their #__id__, so that no exception's or cleaner's own #eql? or #hash is
572
+ # called: an exception class can define them by value, which would cache two of its exceptions
573
+ # together, and a cleaner, such as a test double, need not define them.
574
+ #
575
+ # The cache is replaced rather than changed, since appenders on other threads may be reading it.
576
+ # Appenders that ask at the same moment can each compute the value, so the block must not rely
577
+ # on being called only once.
578
+ # Once the entry is handed to the appenders the cache only grows, so the entry found by #key? is
579
+ # still there when it is read.
580
+ def cached(key)
581
+ return @cache[key] if @cache&.key?(key)
582
+
583
+ # Merged into the cache as it is now: another appender may have added to it meanwhile.
584
+ yield.tap { |value| @cache = (@cache || {}).merge(key => value).freeze }
585
+ end
586
+
587
+ # Returns [String] the value as text in valid UTF-8 (see Utils.encode_utf8_string).
588
+ def utf8(value) = Utils.encode_utf8_string(value.to_s)
589
+
590
+ # Returns [String] the exception's message, without raising, so that log_exception: :partial
591
+ # never replaces the exception being logged with one that its #message raises (see
592
+ # Utils.exception_message).
593
+ def message_of(exception) = Utils.exception_message(exception)
594
+
595
+ # Returns [String] this entry's message, as log_exception: :partial writes it, followed by the
596
+ # label, the class of the exception, named as Utils.exception_name names it, and any more texts,
597
+ # joined once.
598
+ def with_class(label, exception, *more) = Utils.join_texts(message, label, Utils.exception_name(exception), *more)
599
+
600
+ # Returns [String] this entry's message, as log_exception: :partial writes it, followed by the
601
+ # class of an exception that caused the logged one, then its message (see #with_cause_message).
602
+ def with_cause(cause) = with_cause_message(with_class(" -- Cause: ", cause), message_of(cause))
603
+
604
+ # Returns [String] the text followed by the message of an exception that caused the logged one,
605
+ # or the text alone when it already holds that message: as when the message is empty, is the
606
+ # class name that the text ends with (when the exception was raised without a message), or was
607
+ # copied by the exception that wraps it into its own. Compared as UTF-8, so that it never raises.
608
+ def with_cause_message(text, added) = utf8(text).include?(utf8(added)) ? text : Utils.join_texts(text, ": ", added)
609
+
610
+ # Whether a log argument from the Hash returned by a logging block, already checked by
611
+ # .argument?, is assigned to its attribute: only when this entry does not have it yet. As in
612
+ # #extract_arguments, an empty message counts as none.
613
+ def block_attribute?(key, value)
614
+ return message.nil? || message == "" if key == :message
615
+ return exception.nil? && value.is_a?(Exception) if key == :exception
616
+
617
+ ASSIGNABLE_KEYS.include?(key) && public_send(key).nil?
316
618
  end
317
619
  end
318
620
  end