semantic_logger 4.18.0 → 5.1.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +51 -81
  3. data/Rakefile +39 -3
  4. data/docs/api.md +480 -0
  5. data/docs/appenders.md +990 -0
  6. data/docs/config.md +605 -0
  7. data/docs/index.md +197 -0
  8. data/docs/log.md +108 -0
  9. data/docs/metrics.md +168 -0
  10. data/docs/operations.md +400 -0
  11. data/docs/rails.md +816 -0
  12. data/docs/security.md +119 -0
  13. data/docs/testing.md +285 -0
  14. data/docs/upgrading.md +409 -0
  15. data/lib/semantic_logger/appender/async.rb +86 -173
  16. data/lib/semantic_logger/appender/cloudwatch_logs.rb +8 -6
  17. data/lib/semantic_logger/appender/elasticsearch.rb +8 -187
  18. data/lib/semantic_logger/appender/elasticsearch_base.rb +212 -0
  19. data/lib/semantic_logger/appender/elasticsearch_http.rb +16 -9
  20. data/lib/semantic_logger/appender/file.rb +25 -4
  21. data/lib/semantic_logger/appender/graylog.rb +2 -2
  22. data/lib/semantic_logger/appender/http.rb +27 -2
  23. data/lib/semantic_logger/appender/io.rb +8 -4
  24. data/lib/semantic_logger/appender/kafka.rb +2 -2
  25. data/lib/semantic_logger/appender/loki.rb +2 -4
  26. data/lib/semantic_logger/appender/mongodb.rb +3 -6
  27. data/lib/semantic_logger/appender/new_relic.rb +6 -0
  28. data/lib/semantic_logger/appender/new_relic_logs.rb +4 -3
  29. data/lib/semantic_logger/appender/open_telemetry.rb +10 -7
  30. data/lib/semantic_logger/appender/opensearch.rb +36 -0
  31. data/lib/semantic_logger/appender/rabbitmq.rb +5 -4
  32. data/lib/semantic_logger/appender/sentry.rb +5 -0
  33. data/lib/semantic_logger/appender/sentry_ruby.rb +2 -2
  34. data/lib/semantic_logger/appender/splunk.rb +2 -2
  35. data/lib/semantic_logger/appender/splunk_http.rb +3 -3
  36. data/lib/semantic_logger/appender/syslog.rb +11 -7
  37. data/lib/semantic_logger/appender/tcp.rb +4 -3
  38. data/lib/semantic_logger/appender/udp.rb +2 -2
  39. data/lib/semantic_logger/appender/wrapper.rb +5 -4
  40. data/lib/semantic_logger/appender.rb +36 -22
  41. data/lib/semantic_logger/appenders.rb +27 -5
  42. data/lib/semantic_logger/base.rb +100 -23
  43. data/lib/semantic_logger/concerns/compatibility.rb +2 -2
  44. data/lib/semantic_logger/core_ext/process.rb +34 -0
  45. data/lib/semantic_logger/formatters/base.rb +46 -7
  46. data/lib/semantic_logger/formatters/color.rb +9 -3
  47. data/lib/semantic_logger/formatters/default.rb +11 -4
  48. data/lib/semantic_logger/formatters/ecs.rb +151 -0
  49. data/lib/semantic_logger/formatters/fluentd.rb +15 -4
  50. data/lib/semantic_logger/formatters/json.rb +6 -1
  51. data/lib/semantic_logger/formatters/logfmt.rb +6 -4
  52. data/lib/semantic_logger/formatters/loki.rb +4 -4
  53. data/lib/semantic_logger/formatters/open_telemetry.rb +15 -5
  54. data/lib/semantic_logger/formatters/pattern.rb +237 -0
  55. data/lib/semantic_logger/formatters/raw.rb +2 -2
  56. data/lib/semantic_logger/formatters/signalfx.rb +2 -2
  57. data/lib/semantic_logger/formatters/syslog.rb +16 -4
  58. data/lib/semantic_logger/formatters/syslog_cee.rb +3 -2
  59. data/lib/semantic_logger/formatters.rb +2 -0
  60. data/lib/semantic_logger/log.rb +18 -4
  61. data/lib/semantic_logger/logger.rb +2 -2
  62. data/lib/semantic_logger/metric/new_relic.rb +2 -2
  63. data/lib/semantic_logger/metric/signalfx.rb +6 -4
  64. data/lib/semantic_logger/metric/statsd.rb +2 -2
  65. data/lib/semantic_logger/processor.rb +21 -0
  66. data/lib/semantic_logger/queue_processor.rb +372 -0
  67. data/lib/semantic_logger/reporters/minitest.rb +8 -8
  68. data/lib/semantic_logger/semantic_logger.rb +103 -11
  69. data/lib/semantic_logger/subscriber.rb +15 -2
  70. data/lib/semantic_logger/sync_processor.rb +25 -3
  71. data/lib/semantic_logger/test/capture_log_events.rb +3 -3
  72. data/lib/semantic_logger/test/minitest.rb +8 -4
  73. data/lib/semantic_logger/test/rspec.rb +249 -0
  74. data/lib/semantic_logger/utils.rb +83 -4
  75. data/lib/semantic_logger/version.rb +1 -1
  76. data/lib/semantic_logger.rb +9 -0
  77. metadata +28 -8
  78. data/lib/semantic_logger/appender/async_batch.rb +0 -93
data/docs/upgrading.md ADDED
@@ -0,0 +1,409 @@
1
+ ---
2
+ layout: default
3
+ ---
4
+
5
+ ## Upgrading
6
+ {:.no_toc}
7
+
8
+ **Contents**
9
+
10
+ * TOC
11
+ {:toc}
12
+
13
+ ### Upgrading to Semantic Logger v5.1
14
+
15
+ v5.1 deprecates several legacy appenders and one appender option. They all still work in v5.1, but
16
+ each now emits a Ruby deprecation warning and will be **removed in v6**. The warnings use
17
+ `category: :deprecated`, so they are silent by default and appear when deprecation warnings are
18
+ enabled (for example `ruby -W:deprecated`, or Rails development mode). Switch away now to be ready
19
+ for v6.
20
+
21
+ #### Replace the `:sentry` appender with `:sentry_ruby`
22
+
23
+ The `:sentry` appender depends on the end-of-life `sentry-raven` gem. Use the `:sentry_ruby`
24
+ appender, backed by the maintained `sentry-ruby` gem.
25
+
26
+ In your `Gemfile`:
27
+
28
+ ~~~ruby
29
+ # Remove:
30
+ gem "sentry-raven"
31
+ # Add:
32
+ gem "sentry-ruby"
33
+ ~~~
34
+
35
+ When adding the appender:
36
+
37
+ ~~~ruby
38
+ # Before:
39
+ SemanticLogger.add_appender(appender: :sentry)
40
+
41
+ # After:
42
+ SemanticLogger.add_appender(appender: :sentry_ruby)
43
+ ~~~
44
+
45
+ #### Replace the `:new_relic` appender with `:new_relic_logs`
46
+
47
+ The `:new_relic` appender reports `:error` and `:fatal` entries to New Relic as **error events** via
48
+ `newrelic_rpm`. It is superseded by `:new_relic_logs`, which forwards log entries to New Relic Logs:
49
+
50
+ ~~~ruby
51
+ # Before:
52
+ SemanticLogger.add_appender(appender: :new_relic)
53
+
54
+ # After:
55
+ SemanticLogger.add_appender(appender: :new_relic_logs)
56
+ ~~~
57
+
58
+ Note that the behaviour differs. `:new_relic` created New Relic *error events* (and defaulted to the
59
+ `:error` level), whereas `:new_relic_logs` forwards *log messages* to New Relic's log ingestion. Set
60
+ `level:` to match what you want forwarded, and update any New Relic dashboards or alerts that relied
61
+ on the old error events. Both appenders require the `newrelic_rpm` gem.
62
+
63
+ #### Remove the `type:` option from the Elasticsearch and OpenSearch appenders
64
+
65
+ Document `_type` has been unused since Elasticsearch 7, so the `type:` option (on `:elasticsearch`,
66
+ `:elasticsearch_http`, and `:opensearch`) is now ignored on all server versions: the bulk appenders
67
+ no longer send a `_type`, and the `:elasticsearch_http` appender posts to the typeless `_doc`
68
+ endpoint. Passing `type:` logs a deprecation warning. Remove it:
69
+
70
+ ~~~ruby
71
+ # Before:
72
+ SemanticLogger.add_appender(appender: :elasticsearch, url: "http://localhost:9200", type: "log")
73
+
74
+ # After:
75
+ SemanticLogger.add_appender(appender: :elasticsearch, url: "http://localhost:9200")
76
+ ~~~
77
+
78
+ ### Upgrading to Semantic Logger v5.0
79
+
80
+ #### Minimum Ruby version is now 3.2
81
+
82
+ Semantic Logger v5 requires Ruby 3.2 or later. Earlier Ruby versions are end-of-life and are no
83
+ longer supported or tested.
84
+
85
+ If you are on an older Ruby, upgrade Ruby before upgrading Semantic Logger, or stay on the v4.x
86
+ series.
87
+
88
+ #### `SemanticLogger::Appender::AsyncBatch` has been removed
89
+
90
+ The internal asynchronous proxy classes have been consolidated. Batch processing now runs through
91
+ the same `SemanticLogger::Appender::Async` proxy (backed by an internal `QueueProcessor`), so the
92
+ separate `SemanticLogger::Appender::AsyncBatch` class no longer exists.
93
+
94
+ This only affects code that referenced the class directly, which is uncommon since appenders are
95
+ added through `SemanticLogger.add_appender`. The `batch:`, `batch_size:`, and `batch_seconds:`
96
+ options are unchanged:
97
+
98
+ ~~~ruby
99
+ SemanticLogger.add_appender(appender: :http, url: "https://example.com/log", batch: true)
100
+ ~~~
101
+
102
+ What changed:
103
+
104
+ - `SemanticLogger.add_appender(..., batch: true)` now returns a `SemanticLogger::Appender::Async`
105
+ (with `#batch?` returning `true`) instead of a `SemanticLogger::Appender::AsyncBatch`.
106
+ - Referencing the constant `SemanticLogger::Appender::AsyncBatch` now raises `NameError`.
107
+
108
+ If you have a custom appender or test asserting on the proxy class, change
109
+ `instance_of?`/`is_a?(SemanticLogger::Appender::AsyncBatch)` checks to
110
+ `SemanticLogger::Appender::Async` and, if needed, check `appender.batch?`.
111
+
112
+ #### Appenders are reopened automatically after fork
113
+
114
+ Previously, applications that fork (Puma, Unicorn, Spring, Resque, `Process.daemon`, etc.) had to
115
+ call `SemanticLogger.reopen` themselves in an after-fork hook, otherwise the child shared the
116
+ parent's file handles and background thread.
117
+
118
+ In v5 this happens automatically: a `Process._fork` / `Process.daemon` hook calls
119
+ `SemanticLogger.reopen` in the child process. The call is guarded to run once per process.
120
+
121
+ For most applications you can now **remove** the manual reopen hook, for example:
122
+
123
+ ~~~ruby
124
+ # No longer needed in v5 — handled automatically:
125
+ before_fork { SemanticLogger.flush }
126
+ after_fork { SemanticLogger.reopen }
127
+ ~~~
128
+
129
+ If you have a reason to manage this yourself (for example you reopen at a very specific point in
130
+ your boot sequence), disable the automatic behaviour:
131
+
132
+ ~~~ruby
133
+ SemanticLogger.reopen_on_fork = false
134
+ ~~~
135
+
136
+ #### Recommended: enable logger caching
137
+
138
+ By default `SemanticLogger[SomeClass]` returns a **new** `Logger` instance on every call. This means
139
+ that if one part of the code obtains a logger and later changes its `level` (or filter), other
140
+ holders of "the same" logger do not see the change, because they hold different instances.
141
+
142
+ v5 adds opt-in caching so that a `Class` or `Module` maps to a single shared `Logger` instance:
143
+
144
+ ~~~ruby
145
+ SemanticLogger.cache_loggers = true
146
+ ~~~
147
+
148
+ With caching enabled:
149
+
150
+ - `SemanticLogger[MyClass]` and the `Loggable` mixin's `MyClass.logger` return the **same** instance.
151
+ - Changing that logger's level or filter is visible to every holder.
152
+ - Strings (`SemanticLogger["Name"]`) always get a fresh instance, and anonymous classes (no `name`)
153
+ are never cached.
154
+
155
+ Enabling caching is recommended for most applications. It is opt-in (default `false`) to preserve
156
+ existing behaviour for code that relied on getting an independent logger per call. If you need to
157
+ discard cached loggers (for example in tests, or after redefining a class), call
158
+ `SemanticLogger.clear_logger_cache`.
159
+
160
+ #### Control characters are escaped in Syslog output
161
+
162
+ To prevent log-injection via embedded control characters (newlines, escape sequences, etc.), the
163
+ Syslog formatter now escapes control characters in records by default. If you relied on raw control
164
+ characters reaching syslog, this output now differs. The text formatters (default, color) also gain
165
+ an opt-in `escape_control_chars` option (default `false`) for the same protection. See the
166
+ [Security](security.html) page for details.
167
+
168
+ #### `Formatters::Base#cleanse` renamed
169
+
170
+ The internal `SemanticLogger::Formatters::Base#cleanse` method was renamed to
171
+ `#escape_control_characters`. This only affects custom formatters or subclasses that called the old
172
+ method name directly; update them to call `#escape_control_characters`.
173
+
174
+ #### Rails: appenders are now configured in one block
175
+
176
+ If you use [rails_semantic_logger](rails.html), the companion gem's v5 release moves appender
177
+ configuration into a single `config.rails_semantic_logger.appenders do |appenders| ... end` block.
178
+ The v4 options (`format`, `add_file_appender`, `ap_options`, `filter`, `console_logger`) still work
179
+ but are deprecated and will be removed in v6. See
180
+ [Migrating from v4 to v5](rails.html#migrating-from-v4-to-v5) for the full before/after mapping.
181
+
182
+ ### Upgrading to Semantic Logger v4.18
183
+
184
+ #### Async queue is now bounded by default
185
+
186
+ The default `max_queue_size` for async appenders changed from `-1` (unbounded) to `10_000`.
187
+ Under sustained high log volume, messages that exceed the queue limit will be dropped rather than
188
+ causing memory to grow without bound.
189
+
190
+ If your application logs at very high throughput and you were relying on the unbounded default,
191
+ set the limit explicitly when adding each appender:
192
+
193
+ ~~~ruby
194
+ SemanticLogger.add_appender(io: $stdout, async: true, max_queue_size: -1)
195
+ ~~~
196
+
197
+ Alternatively, tune the value to match your application's tolerance for log loss vs. memory usage.
198
+
199
+ #### Invalid exception values are now wrapped
200
+
201
+ Previously, passing a non-`Exception` object to the `exception:` keyword argument would silently
202
+ misbehave. It is now wrapped in an `ArgumentError` with a description of the invalid value and a
203
+ backtrace pointing to the call site:
204
+
205
+ ~~~ruby
206
+ # This previously caused undefined behaviour — now raises a descriptive ArgumentError
207
+ logger.error("Something went wrong", exception: "a plain string")
208
+ ~~~
209
+
210
+ #### New Relic formatter — trace and span metadata
211
+
212
+ Previously, New Relic trace metadata (`trace.id`, `span.id`, `entity.name`, etc.) was captured at
213
+ format time, so it worked with any appender type. In v4.18, this metadata is captured via an
214
+ `on_log` callback that is only registered when `SemanticLogger::Appender::NewRelicLogs` is
215
+ instantiated.
216
+
217
+ If you use a plain IO or File appender with `SemanticLogger::Formatters::NewRelicLogs` as the
218
+ formatter (rather than the dedicated `NewRelicLogs` appender), you must register the callback
219
+ manually in your initializer, otherwise `trace.id`, `span.id`, and `entity.name` will be absent
220
+ from all logs:
221
+
222
+ ~~~ruby
223
+ require "semantic_logger/appender/new_relic_logs"
224
+ SemanticLogger.on_log(SemanticLogger::Appender::NewRelicLogs::CAPTURE_CONTEXT)
225
+ ~~~
226
+
227
+ This line should be added before any log messages are emitted.
228
+
229
+ ---
230
+
231
+ ### Upgrading to Semantic Logger v4.17
232
+
233
+ #### New Relic formatter (breaking changes for New Relic users)
234
+
235
+ The New Relic log formatter (`SemanticLogger::Formatters::NewRelicLogs`) has been significantly
236
+ updated to produce a structure that New Relic can natively parse and index as individual
237
+ attributes. Most users will benefit from richer log correlation in New Relic, but there are
238
+ several breaking changes to be aware of.
239
+
240
+ ##### Log output structure
241
+
242
+ Previously, all semantic fields (`payload`, `tags`, `named_tags`, `metric`, etc.) were serialized
243
+ as a JSON string inside the `message` key. They are now emitted as top-level keys:
244
+
245
+ Before (v4.16):
246
+ ~~~json
247
+ {
248
+ "message": "{\"message\":\"Order processed\",\"payload\":{\"order_id\":123},\"tags\":[],\"named_tags\":{}}",
249
+ "timestamp": 1234567890000,
250
+ "log.level": "INFO"
251
+ }
252
+ ~~~
253
+
254
+ After (v4.17):
255
+ ~~~json
256
+ {
257
+ "message": "Order processed",
258
+ "payload": { "order_id": 123 },
259
+ "timestamp": 1234567890000,
260
+ "logger": { "name": "OrderService" },
261
+ "thread": { "name": "main" }
262
+ }
263
+ ~~~
264
+
265
+ **Impact**: Any New Relic alert queries, dashboards, or NRQL that references fields inside the
266
+ old `message` JSON string (e.g. `message.payload.order_id`) must be updated to reference the
267
+ new top-level keys (e.g. `payload.order_id`).
268
+
269
+ Note that New Relic's log ingestion flattens nested objects. A `payload` value that is itself a
270
+ nested Hash may not be fully indexed as individually searchable attributes. If you need payload
271
+ fields to be queryable in New Relic, promote them to `named_tags` instead:
272
+
273
+ ~~~ruby
274
+ # Payload fields may not be individually queryable in New Relic:
275
+ logger.info "Order processed", order_id: 123, amount: 49.99
276
+
277
+ # Use named_tags for fields you want to query directly in New Relic:
278
+ SemanticLogger.tagged(order_id: 123, amount: 49.99) do
279
+ logger.info "Order processed"
280
+ end
281
+ ~~~
282
+
283
+ ##### named_tags are now merged to the top level
284
+
285
+ Previously `named_tags` were nested inside the `message` JSON string. They are now merged
286
+ directly into the top-level log entry, making them first-class attributes in New Relic.
287
+
288
+ If a named tag key conflicts with an existing top-level key (e.g. `message`, `timestamp`), it is
289
+ dropped and the conflicting key names are recorded under `named_tag_conflicts`.
290
+
291
+ ##### Error, logger, and thread fields restructured
292
+
293
+ Before (v4.16):
294
+ ~~~json
295
+ {
296
+ "error.message": "Something went wrong",
297
+ "error.class": "RuntimeError",
298
+ "error.stack": "...",
299
+ "log.level": "ERROR",
300
+ "logger.name": "OrderService",
301
+ "thread.name": "main"
302
+ }
303
+ ~~~
304
+
305
+ After (v4.17):
306
+ ~~~json
307
+ {
308
+ "error": { "message": "Something went wrong", "class": "RuntimeError", "stack": "..." },
309
+ "logger": { "name": "OrderService" },
310
+ "thread": { "name": "main" }
311
+ }
312
+ ~~~
313
+
314
+ Update any New Relic alert conditions or NRQL queries that reference the old dot-notation keys.
315
+
316
+ #### Suppressing timestamps in formatters
317
+
318
+ v4.17 added `:notime` as an explicit `time_format` value to suppress timestamp output. If you
319
+ were previously passing `time_format: nil` expecting it to suppress output, use `:notime` instead:
320
+
321
+ ~~~ruby
322
+ SemanticLogger.add_appender(io: $stdout, formatter: MyFormatter.new(time_format: :notime))
323
+ ~~~
324
+
325
+ ---
326
+
327
+ ### Upgrading to Semantic Logger v4.9
328
+
329
+ These changes should not be noticeable by the majority of users of Semantic Logger, since
330
+ they are to the internal API. It is possible that advanced users may be using these internal
331
+ API's directly.
332
+
333
+ This does not affect any calls to the public api `SemanticLogger.add_appender`.
334
+
335
+ File and IO are now separate appenders. When creating the File appender explicitly, its arguments
336
+ have changed. For example, when requesting an IO stream, it needs to be changed from:
337
+
338
+ ~~~ruby
339
+ SemanticLogger::Appender::File.new(io: $stderr)
340
+ ~~~
341
+ to:
342
+ ~~~ruby
343
+ SemanticLogger::Appender::IO.new($stderr)
344
+ ~~~
345
+
346
+ Additionally, this needs to be changed from:
347
+ ~~~ruby
348
+ SemanticLogger::Appender::File.new(file_name: "file.log")
349
+ ~~~
350
+ to:
351
+ ~~~ruby
352
+ SemanticLogger::Appender::File.new("file.log")
353
+ ~~~
354
+
355
+ Rails Semantic Logger, if used, needs to be upgraded to v4.9 when upgrading to Semantic Logger v4.9.
356
+
357
+ ---
358
+
359
+ ### Upgrading to Semantic Logger v4.4
360
+
361
+ With some forking frameworks it is necessary to call `reopen` after the fork. With v4.4 the
362
+ workaround for Ruby 2.5 crashes is no longer needed.
363
+ I.e. Please remove the following line if being called anywhere:
364
+
365
+ ~~~ruby
366
+ SemanticLogger::Processor.instance.instance_variable_set(:@queue, Queue.new)
367
+ ~~~
368
+
369
+ ---
370
+
371
+ ### Upgrading to Semantic Logger v4.0
372
+
373
+ The following changes need to be made when upgrading to V4:
374
+ - Ruby V2.3 / JRuby V9.1 is now the minimum runtime version.
375
+ - Replace calls to `Logger#with_payload` with `SemanticLogger.named_tagged`.
376
+ - Replace calls to `Logger#payload` with `SemanticLogger.named_tags`.
377
+ - MongoDB Appender requires Mongo Ruby Client V2 or greater.
378
+ - Appenders now write payload data in a separate `:payload` tag instead of mixing them
379
+ directly into the root elements to avoid name clashes.
380
+
381
+ As a result any calls like the following:
382
+
383
+ ~~~ruby
384
+ logger.debug foo: 'foo', bar: 'bar'
385
+ ~~~
386
+
387
+ Must be replaced with the following in v4:
388
+
389
+ ~~~ruby
390
+ logger.debug payload: {foo: 'foo', bar: 'bar'}
391
+ ~~~
392
+
393
+ Similarly, for measure blocks:
394
+
395
+ ~~~ruby
396
+ logger.measure_info('How long is the sleep', foo: 'foo', bar: 'bar') { sleep 1 }
397
+ ~~~
398
+
399
+ Must be replaced with the following in v4:
400
+
401
+ ~~~ruby
402
+ logger.measure_info('How long is the sleep', payload: {foo: 'foo', bar: 'bar'}) { sleep 1 }
403
+ ~~~
404
+
405
+ The common log call has not changed, and the payload is still logged directly:
406
+
407
+ ~~~ruby
408
+ logger.debug('log this', foo: 'foo', bar: 'bar')
409
+ ~~~
@@ -2,28 +2,39 @@ require "forwardable"
2
2
 
3
3
  module SemanticLogger
4
4
  module Appender
5
- # Allow any appender to run asynchronously in a separate thread.
5
+ # Proxy that allows any appender to run asynchronously in a separate thread.
6
+ #
7
+ # The worker thread and the in-memory queue are owned by an internal
8
+ # SemanticLogger::QueueProcessor. This proxy forwards log/flush/close/reopen on to the
9
+ # processor, and forwards the remaining appender methods (name, level, ...) directly to
10
+ # the wrapped appender so they keep executing on the caller's thread.
6
11
  class Async
7
12
  extend Forwardable
8
13
 
9
- attr_accessor :lag_check_interval, :lag_threshold_s
10
- attr_reader :queue, :appender, :max_queue_size
14
+ attr_reader :appender, :processor
11
15
 
12
- # Forward methods that can be called directly
13
- def_delegator :@appender, :name
14
- def_delegator :@appender, :should_log?
15
- def_delegator :@appender, :filter
16
- def_delegator :@appender, :host
17
- def_delegator :@appender, :application
18
- def_delegator :@appender, :environment
19
- def_delegator :@appender, :level
20
- def_delegator :@appender, :level=
21
- def_delegator :@appender, :logger
22
- def_delegator :@appender, :logger=
16
+ # Methods forwarded directly to the wrapped appender (run on the caller's thread).
17
+ def_delegators :@appender,
18
+ :name, :should_log?, :filter, :host, :application, :environment,
19
+ :level, :level=, :logger, :logger=, :console_stream, :console_output?
20
+
21
+ # Methods forwarded to the queue processor that owns the thread and queue.
22
+ # Tuning options (max_queue_size, batch_size, non_blocking, ...) are set once at
23
+ # 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
+ def_delegators :@processor,
26
+ :log, :flush, :close, :thread, :active?, :queue, :max_queue_size,
27
+ :capped?, :non_blocking?, :batch?,
28
+ :lag_check_interval, :lag_check_interval=,
29
+ :lag_threshold_s, :lag_threshold_s=,
30
+ :processed_count, :dropped_count
23
31
 
24
32
  # Appender proxy to allow an existing appender to run asynchronously in a separate thread.
25
33
  #
26
34
  # Parameters:
35
+ # appender: [SemanticLogger::Subscriber]
36
+ # The appender to log to in a separate thread.
37
+ #
27
38
  # max_queue_size: [Integer]
28
39
  # The maximum number of log messages to hold on the queue before blocking attempts to add to the queue.
29
40
  # -1: The queue size is uncapped and will never block no matter how long the queue is.
@@ -36,172 +47,74 @@ module SemanticLogger
36
47
  # lag_check_interval: [Integer]
37
48
  # Number of messages to process before checking for slow logging.
38
49
  # Default: 1,000
39
- def initialize(appender:,
40
- max_queue_size: 10_000,
41
- lag_check_interval: 1_000,
42
- lag_threshold_s: 30)
43
- @appender = appender
44
- @lag_check_interval = lag_check_interval
45
- @lag_threshold_s = lag_threshold_s
46
- @thread = nil
47
- @max_queue_size = max_queue_size
48
- create_queue
49
- thread
50
+ # Note: Not applicable when batch: true.
51
+ #
52
+ # batch: [true|false]
53
+ # Process log messages in batches via the appender's #batch method, instead of one at a time.
54
+ # The appender must implement #batch.
55
+ # Default: false
56
+ #
57
+ # batch_size: [Integer]
58
+ # Maximum number of messages to batch up before sending.
59
+ # Default: 300
60
+ # Note: Only applicable when batch: true.
61
+ #
62
+ # batch_seconds: [Integer]
63
+ # Maximum number of seconds between sending batches.
64
+ # Default: 5
65
+ # Note: Only applicable when batch: true.
66
+ #
67
+ # non_blocking: [true|false]
68
+ # Whether to drop log messages instead of blocking the calling thread when the queue is full.
69
+ # When true and the queue is capped, attempts to add to a full queue return immediately and
70
+ # the message is dropped. The number of dropped messages is logged to the internal logger
71
+ # periodically (see dropped_message_report_seconds). Only applies to a capped queue.
72
+ # Default: false
73
+ #
74
+ # 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.
77
+ # Default: 30
78
+ #
79
+ # async_max_retries: [Integer]
80
+ # Maximum number of consecutive times to restart the worker thread (with a back-off)
81
+ # after it raises an exception while processing messages, before giving up and stopping
82
+ # the thread. The counter resets after any message is processed successfully.
83
+ # -1: Retry indefinitely and never stop the thread (the pre-v5 behaviour).
84
+ # Default: 100
85
+ def initialize(appender:, **args)
86
+ @appender = appender
87
+ @processor = QueueProcessor.start(appender: appender, **args)
50
88
  end
51
89
 
52
- # Re-open appender after a fork
90
+ # Re-open appender after a fork.
53
91
  def reopen
54
- # Workaround CRuby crash on fork by recreating queue on reopen
55
- # https://github.com/reidmorrison/semantic_logger/issues/103
56
- @queue&.close
57
- create_queue
58
-
59
92
  appender.reopen if appender.respond_to?(:reopen)
60
-
61
- @thread&.kill if @thread&.alive?
62
- @thread = Thread.new { process }
63
- end
64
-
65
- # Returns [true|false] if the queue has a capped size.
66
- def capped?
67
- @capped
93
+ processor.reopen
68
94
  end
69
95
 
70
- # Returns [Thread] the worker thread.
96
+ # Returns [Hash] operational statistics for this appender.
71
97
  #
72
- # Starts the worker thread if not running.
73
- def thread
74
- return @thread if @thread&.alive?
75
-
76
- @thread = Thread.new { process }
77
- end
78
-
79
- # Returns true if the worker thread is active
80
- def active?
81
- @thread&.alive?
82
- end
83
-
84
- # Add log message for processing.
85
- def log(log)
86
- queue << log
87
- end
88
-
89
- # Flush all queued log entries disk, database, etc.
90
- # All queued log messages are written and then each appender is flushed in turn.
91
- def flush
92
- submit_request(:flush)
93
- end
94
-
95
- # Close all appenders and flush any outstanding messages.
96
- def close
97
- # TODO: Prevent new close requests once this appender has been closed.
98
- submit_request(:close)
99
- end
100
-
101
- private
102
-
103
- def create_queue
104
- if max_queue_size == -1
105
- @queue = Queue.new
106
- @capped = false
107
- else
108
- @queue = SizedQueue.new(max_queue_size)
109
- @capped = true
110
- end
111
- end
112
-
113
- # Separate thread for batching up log messages before writing.
114
- def process
115
- # This thread is designed to never go down unless the main thread terminates
116
- # or the appender is closed.
117
- Thread.current.name = logger.name
118
- logger.trace "Async: Appender thread active"
119
- begin
120
- process_messages
121
- rescue StandardError => e
122
- # This block may be called after the file handles have been released by Ruby
123
- begin
124
- logger.error("Async: Restarting due to exception", e)
125
- rescue StandardError
126
- nil
127
- end
128
- retry
129
- rescue Exception => e
130
- # This block may be called after the file handles have been released by Ruby
131
- begin
132
- logger.error("Async: Stopping due to fatal exception", e)
133
- rescue StandardError
134
- nil
135
- end
136
- ensure
137
- @thread = nil
138
- # This block may be called after the file handles have been released by Ruby
139
- begin
140
- logger.trace("Async: Thread has stopped")
141
- rescue StandardError
142
- nil
143
- end
144
- end
145
- end
146
-
147
- def process_messages
148
- count = 0
149
- while (message = queue.pop)
150
- if message.is_a?(Log)
151
- appender.log(message)
152
- count += 1
153
- # Check every few log messages whether this appender thread is falling behind
154
- if count > lag_check_interval
155
- check_lag(message)
156
- count = 0
157
- end
158
- else
159
- break unless process_message(message)
160
- end
161
- end
162
- logger.trace "Async: Queue Closed"
163
- end
164
-
165
- # Returns false when message processing should be stopped
166
- def process_message(message)
167
- case message[:command]
168
- when :flush
169
- appender.flush
170
- message[:reply_queue] << true if message[:reply_queue]
171
- when :close
172
- appender.close
173
- message[:reply_queue] << true if message[:reply_queue]
174
- return false
175
- else
176
- logger.warn "Async: Appender thread: Ignoring unknown command: #{message[:command]}"
177
- end
178
- true
179
- end
180
-
181
- def check_lag(log)
182
- diff = Time.now - log.time
183
- return unless diff > lag_threshold_s
184
-
185
- logger.warn "Async: Appender thread has fallen behind by #{diff} seconds with #{queue.size} messages queued up. Consider reducing the log level or changing the appenders"
186
- end
187
-
188
- # Submit command and wait for reply
189
- def submit_request(command)
190
- return false unless active?
191
-
192
- queue_size = queue.size
193
- msg = "Async: Queued log messages: #{queue_size}, running command: #{command}"
194
- if queue_size > 1_000
195
- logger.warn msg
196
- elsif queue_size > 100
197
- logger.info msg
198
- elsif queue_size.positive?
199
- logger.trace msg
200
- end
201
-
202
- reply_queue = Queue.new
203
- queue << {command: command, reply_queue: reply_queue}
204
- reply_queue.pop
98
+ # name: [String] Name of the wrapped appender.
99
+ # async: [true] This appender logs asynchronously via a separate thread.
100
+ # thread_active: [Boolean] Whether the worker thread is currently running.
101
+ # queue_size: [Integer] Number of log messages currently waiting to be written.
102
+ # capped: [Boolean] Whether the queue has a maximum size.
103
+ # max_queue_size: [Integer] Maximum queue size, or nil when uncapped.
104
+ # processed: [Integer] Cumulative number of log messages written since startup.
105
+ # dropped: [Integer] Cumulative number of log messages dropped because the queue
106
+ # was full (only possible when non_blocking is enabled).
107
+ def stats
108
+ {
109
+ name: name,
110
+ async: true,
111
+ thread_active: active? || false,
112
+ queue_size: queue.size,
113
+ capped: capped?,
114
+ max_queue_size: capped? ? max_queue_size : nil,
115
+ processed: processed_count,
116
+ dropped: dropped_count
117
+ }
205
118
  end
206
119
  end
207
120
  end