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
@@ -16,18 +16,21 @@ module SemanticLogger
16
16
  # Methods forwarded directly to the wrapped appender (run on the caller's thread).
17
17
  def_delegators :@appender,
18
18
  :name, :should_log?, :filter, :host, :application, :environment,
19
- :level, :level=, :logger, :logger=, :console_stream, :console_output?
19
+ :level, :level=, :formatter, :formatter=, :logger, :logger=, :console_stream,
20
+ :console_output?
20
21
 
21
22
  # Methods forwarded to the queue processor that owns the thread and queue.
22
23
  # Tuning options (max_queue_size, batch_size, non_blocking, ...) are set once at
23
24
  # construction via SemanticLogger.add_appender, so only the values that callers actually
24
- # read back are re-exposed here. lag_* backs the public SemanticLogger.lag_* API.
25
+ # read back are re-exposed here. lag_* and non_blocking= back the public
26
+ # SemanticLogger.lag_* and SemanticLogger.non_blocking= API on the main Processor.
25
27
  def_delegators :@processor,
26
- :log, :flush, :close, :thread, :active?, :queue, :max_queue_size,
27
- :capped?, :non_blocking?, :batch?,
28
+ :log, :flush, :close, :renew_after_fork, :process_exiting=, :thread, :active?,
29
+ :worker_thread?, :holding_up?,
30
+ :queue, :max_queue_size, :capped?, :non_blocking?, :non_blocking=, :batch?,
28
31
  :lag_check_interval, :lag_check_interval=,
29
32
  :lag_threshold_s, :lag_threshold_s=,
30
- :processed_count, :dropped_count
33
+ :processed_count, :dropped_count, :failed_count
31
34
 
32
35
  # Appender proxy to allow an existing appender to run asynchronously in a separate thread.
33
36
  #
@@ -72,24 +75,47 @@ module SemanticLogger
72
75
  # Default: false
73
76
  #
74
77
  # dropped_message_report_seconds: [Integer]
75
- # When non_blocking is enabled, log the count of dropped messages to the internal logger
76
- # at most once every this number of seconds.
78
+ # Log the count of messages dropped because the queue was full, with non_blocking or once
79
+ # the worker thread has stopped (see async_max_retries), to the internal logger at most
80
+ # once every this number of seconds. Also limits how often messages discarded because
81
+ # they could not be written are reported, after the first.
77
82
  # Default: 30
78
83
  #
79
84
  # async_max_retries: [Integer]
80
85
  # Maximum number of consecutive times to restart the worker thread (with a back-off)
81
86
  # after it raises an exception while processing messages, before giving up and stopping
82
87
  # the thread. The counter resets after any message is processed successfully.
88
+ # Once stopped, messages are dropped when the queue is full, rather than block.
83
89
  # -1: Retry indefinitely and never stop the thread (the pre-v5 behaviour).
84
90
  # Default: 100
91
+ #
92
+ # The proxy also answers #wrapped_logger, the logger that the appender writes to, when the
93
+ # appender has one, such as one added with `logger:`, so that it is found the same way with or
94
+ # without async: true. The proxy of any other appender does not respond to it.
85
95
  def initialize(appender:, **args)
86
96
  @appender = appender
87
97
  @processor = QueueProcessor.start(appender: appender, **args)
98
+ define_singleton_method(:wrapped_logger) { @appender.wrapped_logger } if appender.respond_to?(:wrapped_logger)
99
+ end
100
+
101
+ # Returns [String] the class and object address of this proxy, whether it batches, and the
102
+ # wrapped appender's own #inspect, which shows only what that appender says is safe, but none of
103
+ # the instance variables of this proxy or its queue processor. See Subscriber#inspect.
104
+ def inspect
105
+ address = Kernel.instance_method(:to_s).bind_call(self).delete_suffix(">")
106
+ "#{address} batch=#{batch?} appender=#{appender.inspect}>"
88
107
  end
89
108
 
90
- # Re-open appender after a fork.
109
+ # Re-open the wrapped appender and the queue processor, after a fork, or within the same
110
+ # process, such as after a log rotation (see QueueProcessor#reopen).
111
+ #
112
+ # The wrapped appender is reopened by the worker thread, before it writes again, so that it
113
+ # is never reopened while it is writing, and not in a signal trap, from which this is often
114
+ # called. So this returns before it has reopened, and a reopen that fails, such as for a server
115
+ # name that no longer resolves, is reported by the worker thread, which carries on. After a
116
+ # fork, the child then always has a worker thread, which reopens the appender before it
117
+ # writes anything.
91
118
  def reopen
92
- appender.reopen if appender.respond_to?(:reopen)
93
119
  processor.reopen
94
120
  end
95
121
 
@@ -103,7 +129,11 @@ module SemanticLogger
103
129
  # max_queue_size: [Integer] Maximum queue size, or nil when uncapped.
104
130
  # processed: [Integer] Cumulative number of log messages written since startup.
105
131
  # dropped: [Integer] Cumulative number of log messages dropped because the queue
106
- # was full (only possible when non_blocking is enabled).
132
+ # was full: with non_blocking enabled, or once the worker
133
+ # thread has stopped (see async_max_retries).
134
+ # failed: [Integer] Cumulative number of log messages discarded because they
135
+ # could not be written, whether their content or the
136
+ # destination was at fault (see Subscriber#message_error?).
107
137
  def stats
108
138
  {
109
139
  name: name,
@@ -113,7 +143,8 @@ module SemanticLogger
113
143
  capped: capped?,
114
144
  max_queue_size: capped? ? max_queue_size : nil,
115
145
  processed: processed_count,
116
- dropped: dropped_count
146
+ dropped: dropped_count,
147
+ failed: failed_count
117
148
  }
118
149
  end
119
150
  end
@@ -56,7 +56,12 @@ module SemanticLogger
56
56
 
57
57
  # Send error messages as Runtime exceptions
58
58
  exception = extract_exception(log)
59
- hash = formatter.call(log, self)
59
+ # Bugsnag replaces each byte of text that is not valid UTF-8 with U+FFFD, including binary
60
+ # text that holds UTF-8, such as a response body, so the data is sent as a copy with its
61
+ # text converted to valid UTF-8, as the JSON formatters write it, and a Hash or Array nested
62
+ # too deeply, or that holds itself, cut off there as they cut it off (see
63
+ # Utils.encode_utf8). Any other object is sent as it is, for Bugsnag to clean.
64
+ hash = format_log(log) { |data| Utils.encode_utf8(data) }
60
65
  bugsnag_notify(exception, hash, log_level(log.level))
61
66
  true
62
67
  end
@@ -82,7 +87,7 @@ module SemanticLogger
82
87
  return log.exception
83
88
  end
84
89
 
85
- error = RuntimeError.new(log.message)
90
+ error = RuntimeError.new(log.message && Utils.encode_utf8_string(log.message.to_s))
86
91
  error.set_backtrace(log.backtrace) if log.backtrace
87
92
  error
88
93
  end
@@ -21,6 +21,13 @@ require "concurrent"
21
21
  module SemanticLogger
22
22
  module Appender
23
23
  class CloudwatchLogs < SemanticLogger::Subscriber
24
+ # PutLogEvents limits, from the AWS documentation: a batch holds at most MAX_BATCH_EVENTS
25
+ # events, and at most MAX_BATCH_BYTES counting each event's message in UTF-8 plus
26
+ # EVENT_OVERHEAD_BYTES, in chronological order.
27
+ MAX_BATCH_BYTES = 1_048_576
28
+ MAX_BATCH_EVENTS = 10_000
29
+ EVENT_OVERHEAD_BYTES = 26
30
+
24
31
  attr_reader :client_kwargs, :group, :create_group, :create_stream,
25
32
  :force_flush_interval_seconds, :max_buffered_events,
26
33
  :task, :client, :buffered_logs
@@ -80,29 +87,55 @@ module SemanticLogger
80
87
  end
81
88
 
82
89
  # Method called to log an event
90
+ #
91
+ # Formats the log message now, so that one that cannot be formatted, or that CloudWatch Logs
92
+ # would reject, raises here for that message alone, and the buffer only holds log events
93
+ # ready to send.
83
94
  def log(log)
84
- buffered_logs << log
85
-
95
+ buffered_logs << log_event(log)
86
96
  put_log_events if buffered_logs.size >= max_buffered_events
97
+ true
87
98
  end
88
99
 
100
+ # Sends the buffered log messages on the calling thread, rather than waiting for the timer.
89
101
  def flush
90
- task.execute while buffered_logs.size.positive?
102
+ put_log_events while buffered_logs.size.positive?
91
103
  end
92
104
 
105
+ # Shuts down the timer, and sends the buffered log events, such as when the appender is removed,
106
+ # which does not flush it first. It has no timer when building the client failed as it was reopened
107
+ # after a fork.
108
+ #
109
+ # In a forked child that has not reopened, such as one that removes the appender before its reopen
110
+ # has run, it first forgets the timer and the buffered log events it inherited, which the parent
111
+ # sends (see #reopen), so that it sends only its own.
93
112
  def close
94
- task.shutdown
113
+ forget_inherited
114
+ task&.shutdown
115
+ flush
95
116
  end
96
117
 
118
+ # Builds a new client, starts a new timer that sends the buffered log events every
119
+ # force_flush_interval_seconds, and then shuts down the timer it replaces, such as after a log
120
+ # rotation. The buffered log events are kept, for the new timer to send. When building the client
121
+ # fails, it raises, and keeps the client and timer it has. An error shutting down the replaced
122
+ # timer is reported to the internal logger, rather than raised.
123
+ #
124
+ # After a fork, the child starts with no buffered log events, since the parent sends those it
125
+ # had, and forgets the timer it inherited, without shutting it down: concurrent-ruby drops the
126
+ # parent's scheduled runs in the child, so that timer never runs there. When building the client
127
+ # fails in the child, the appender has no timer, and sends the buffered log events only once
128
+ # max_buffered_events are buffered, or it is flushed, until a reopen succeeds.
97
129
  def reopen
98
- @buffered_logs = Concurrent::Array.new
99
- @client = Aws::CloudWatchLogs::Client.new(client_kwargs)
100
-
101
- @task = Concurrent::TimerTask.new(execution_interval: force_flush_interval_seconds,
102
- interval_type: :fixed_rate) do
130
+ forget_inherited
131
+ @client = Aws::CloudWatchLogs::Client.new(client_kwargs)
132
+ replaced = @task
133
+ @task = Concurrent::TimerTask.new(execution_interval: force_flush_interval_seconds,
134
+ interval_type: :fixed_rate) do
103
135
  put_log_events
104
136
  end
105
137
  @task.execute
138
+ shut_down_replaced(replaced)
106
139
  end
107
140
 
108
141
  # Use JSON Formatter by default
@@ -110,38 +143,140 @@ module SemanticLogger
110
143
  SemanticLogger::Formatters::Json.new
111
144
  end
112
145
 
146
+ # Only the log group and stream: the client options can hold AWS credentials. See
147
+ # Subscriber#inspect.
148
+ def inspect_details
149
+ "group=#{group.inspect} stream=#{stream.inspect}"
150
+ end
151
+
113
152
  private
114
153
 
154
+ # Starts with no buffered log events, and no timer, in a process other than the one that buffered the
155
+ # log events and started the timer: when the appender is created, and in a child process after a fork,
156
+ # where it forgets those of the parent. Records the process. See #reopen.
157
+ def forget_inherited
158
+ return if @pid == ::Process.pid
159
+
160
+ @task = nil
161
+ @buffered_logs = Concurrent::Array.new
162
+ @pid = ::Process.pid
163
+ end
164
+
165
+ # Shuts down the timer that a reopen replaced, if any. Reports an error to the internal logger as a
166
+ # warning, rather than raising it, since the new timer already sends the buffered log events.
167
+ def shut_down_replaced(task)
168
+ task&.shutdown
169
+ rescue StandardError => e
170
+ logger.warn("Could not shut down the timer that a reopen replaced", e)
171
+ end
172
+
173
+ # Returns [Hash] the PutLogEvents log event for the log message.
174
+ def log_event(log)
175
+ {timestamp: (log.time.to_f * 1000).floor, message: event_message(format_log(log))}
176
+ end
177
+
178
+ # Returns [String] the formatted log message in UTF-8, cut short to the most that a batch can
179
+ # hold.
180
+ #
181
+ # Raises FormatError for a message that CloudWatch Logs would reject, together with every
182
+ # other message in the same request: one that is not a String, or is empty.
183
+ def event_message(message)
184
+ unless message.is_a?(String)
185
+ raise(FormatError, "Could not format the log message (the formatter returned a #{message.class})")
186
+ end
187
+
188
+ message = Utils.encode_utf8_string(message)
189
+ raise(FormatError, "Could not format the log message (it is empty)") if message.empty?
190
+
191
+ limit = MAX_BATCH_BYTES - EVENT_OVERHEAD_BYTES
192
+ message.bytesize <= limit ? message : message.byteslice(0, limit).scrub("")
193
+ end
194
+
195
+ # Sends the buffered log events, in as many requests as the PutLogEvents limits need.
196
+ #
197
+ # A request that fails is reported to the internal logger rather than raised: this usually
198
+ # runs on the timer thread, which discards errors, and the log events were already taken off
199
+ # the buffer, so AWS rejecting a batch, for example one over the size limit, lost every
200
+ # message in it without a trace.
115
201
  def put_log_events
116
- logs = buffered_logs.shift(max_buffered_events)
202
+ events = buffered_logs.shift(max_buffered_events)
203
+ return if events.none?
117
204
 
118
- return if logs.none?
205
+ batches(events).each { |batch| put_batch(batch) }
206
+ end
119
207
 
208
+ # Returns [Array<Array<Hash>>] the log events in chronological order, as PutLogEvents requires,
209
+ # split into batches that it accepts.
210
+ def batches(events)
211
+ batches = [[]]
212
+ bytes = 0
213
+ # Keeps the order of log events with the same timestamp.
214
+ events.each_with_index.sort_by { |event, index| [event[:timestamp], index] }.each do |event, _index|
215
+ size = event[:message].bytesize + EVENT_OVERHEAD_BYTES
216
+ if batches.last.size >= MAX_BATCH_EVENTS || bytes + size > MAX_BATCH_BYTES
217
+ batches << []
218
+ bytes = 0
219
+ end
220
+ batches.last << event
221
+ bytes += size
222
+ end
223
+ batches.reject(&:empty?)
224
+ end
225
+
226
+ # Sends one batch, reporting any failure to the internal logger, so that the other batches are
227
+ # still sent.
228
+ def put_batch(events)
229
+ response = send_batch(events)
230
+ report_rejected_events(events, response.rejected_log_events_info)
231
+ rescue StandardError => e
232
+ logger.error("Could not send #{events.size} log message(s) to CloudWatch Logs", e)
233
+ end
234
+
235
+ # Returns the PutLogEvents response, after creating the log group or stream when it is missing
236
+ # and this appender may create it.
237
+ def send_batch(events)
238
+ created = []
120
239
  begin
121
- client.put_log_events({
122
- log_group_name: group,
123
- log_stream_name: stream,
124
- log_events: logs.map do |log|
125
- {
126
- timestamp: (log.time.to_f * 1000).floor,
127
- message: formatter.call(log, self)
128
- }
129
- end
130
- })
240
+ client.put_log_events(log_group_name: group, log_stream_name: stream, log_events: events)
131
241
  rescue Aws::CloudWatchLogs::Errors::ResourceNotFoundException => e
132
- if e.message.include?("log group does not exist.") && create_group
133
- client.create_log_group({
134
- log_group_name: group
135
- })
136
- retry
137
- elsif e.message.include?("log stream does not exist.") && create_stream
138
- client.create_log_stream({
139
- log_group_name: group,
140
- log_stream_name: stream
141
- })
142
- retry
143
- end
242
+ resource = missing_resource(e)
243
+ raise if resource.nil? || created.include?(resource)
244
+
245
+ create(resource)
246
+ created << resource
247
+ retry
248
+ end
249
+ end
250
+
251
+ # Returns [:group | :stream | nil] the missing resource that this appender may create.
252
+ def missing_resource(exception)
253
+ if exception.message.include?("log group does not exist.") && create_group
254
+ :group
255
+ elsif exception.message.include?("log stream does not exist.") && create_stream
256
+ :stream
257
+ end
258
+ end
259
+
260
+ def create(resource)
261
+ if resource == :group
262
+ client.create_log_group(log_group_name: group)
263
+ else
264
+ client.create_log_stream(log_group_name: group, log_stream_name: stream)
144
265
  end
266
+ rescue Aws::CloudWatchLogs::Errors::ResourceAlreadyExistsException
267
+ # Created meanwhile, for example by another process logging to the same log group.
268
+ nil
269
+ end
270
+
271
+ # PutLogEvents accepts a request in which it rejects some of the log events: those more than 2
272
+ # hours in the future, older than 14 days, or older than the log group's retention period.
273
+ def report_rejected_events(events, rejected)
274
+ return unless rejected
275
+
276
+ logger.warn(
277
+ "CloudWatch Logs rejected some of #{events.size} log message(s) as too new, too old, or expired",
278
+ rejected.to_h
279
+ )
145
280
  end
146
281
 
147
282
  def stream