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
data/docs/security.md CHANGED
@@ -1,9 +1,12 @@
1
1
  ---
2
2
  layout: default
3
+ title: Security
4
+ description: >-
5
+ Keeping logs trustworthy: log injection and forging, redacting sensitive
6
+ data, transport encryption, log file permissions, and the gem's dependency
7
+ footprint.
3
8
  ---
4
9
 
5
- ## Security
6
- {:.no_toc}
7
10
 
8
11
  **Contents**
9
12
 
@@ -25,6 +28,10 @@ characters in that data can be abused:
25
28
  record into two at a collector that frames records with a separator.
26
29
  * An ANSI escape sequence can spoof or hide terminal output when the log is viewed in
27
30
  a terminal.
31
+ * A Unicode line or paragraph separator (U+2028, U+2029) starts a new line in editors,
32
+ browsers, and some log viewers, and a bidirectional control, such as the right-to-left
33
+ override (U+202E), can make a forged entry, such as `user=admin`, read in another order
34
+ than it was written.
28
35
 
29
36
  The structured formatters, such as `:json`, are **not** affected, because JSON encoding
30
37
  always escapes control characters. They are the recommended choice when forwarding logs
@@ -34,7 +41,7 @@ By design the human readable text formatters (`:default` and `:color`) preserve
34
41
  newlines and ANSI color codes, since multi-line and colorized output is useful when
35
42
  reading logs locally. When the text output may contain untrusted data, enable the
36
43
  `escape_control_chars` option to replace control characters with a printable, escaped
37
- form (for example a newline becomes `\n`):
44
+ form (for example a newline becomes `\n`, and the right-to-left override `\u202e`):
38
45
 
39
46
  ~~~ruby
40
47
  SemanticLogger.add_appender(file_name: "production.log", formatter: {default: {escape_control_chars: true}})
@@ -52,45 +59,215 @@ The record-framed network appenders are already safe by default:
52
59
  If you replace the formatter on any of these appenders with a text formatter, enable
53
60
  `escape_control_chars` as shown above.
54
61
 
62
+ ### Logging untrusted hashes
63
+
64
+ A hash passed after the message is the payload, but a few of its keys are also log arguments:
65
+ `duration`, `min_duration`, `metric`, `metric_amount`, `exception`, `log_exception`, and so on.
66
+ That is convenient for code you write, but when the hash holds untrusted data, such as parsed
67
+ request parameters or a webhook body with Symbol keys, it can set those arguments too. For
68
+ example `{duration: 0, min_duration: 1}` would suppress the entry.
69
+
70
+ Semantic Logger only uses such a key as an argument when its value is valid for it: for example
71
+ `duration` must be a finite real number, `backtrace` an Array of Strings, and `on_exception_level` a
72
+ valid level. Any other value stays in the payload as data, and a `nil` value is ignored, so an
73
+ untrusted hash passed to a level method such as `info` can never make the logging call raise.
74
+ A valid `backtrace` also sets where the entry is recorded as logged: its file name, line number, and,
75
+ with [`call_site_level`](config.html#recording-where-each-entry-was-logged), its method. A
76
+ `call_site` key can only leave out the recorded call site, with `false`: the values that set one are
77
+ Ruby objects that parsed data cannot hold.
78
+
79
+ To make sure none of its keys are treated as arguments, pass it as the explicit `payload:`. Any other
80
+ keys supplied alongside an explicit `payload:` are merged into it, and win over the explicit
81
+ payload's values of the same name, so that the untrusted data cannot replace a value your code
82
+ supplies. A String key, as `JSON.parse` returns without `symbolize_names`, has the same name as the
83
+ Symbol key it spells:
84
+
85
+ ~~~ruby
86
+ # The hash is logged as-is, and none of its keys are interpreted. Its own account_id, if any,
87
+ # cannot replace the one supplied here:
88
+ logger.info("Webhook received", payload: JSON.parse(body, symbolize_names: true), account_id: account.id)
89
+ ~~~
90
+
91
+ A hash returned from a logging block, such as
92
+ `logger.debug("Webhook received") { JSON.parse(body, symbolize_names: true) }`, is checked the
93
+ same way, and never replaces a value the log call supplied. A key is only used as an argument when
94
+ its value is valid for it and the log entry does not have that argument yet: an empty `message`
95
+ counts as none, and a backtrace captured at the `backtrace_level` counts as supplied. Its `payload`
96
+ is only used when it is a Hash. Every other key, including an argument the entry already has, is
97
+ added to the payload without replacing the log call's values, and wins over the block's own
98
+ `payload` values of the same name. The caller's own payload Hash is left unchanged.
99
+
100
+ The options of a `measure_*` call are checked the same way: an option with a value that is not valid
101
+ for it is ignored, and its default is used. Keys that are not measure options are not logged at all,
102
+ so pass untrusted data to a measure call as its `payload:` too. A measure call without a block still
103
+ raises unless it is given a valid `:duration`.
104
+
55
105
  ### Redacting sensitive data
56
106
 
57
- Semantic Logger does not automatically redact secrets or personal information; it logs
58
- the message and payload it is given. Avoid logging passwords, tokens, full credit card
59
- numbers, and similar values in the first place.
107
+ Semantic Logger logs the message and payload it is given. Avoid logging passwords, tokens, full
108
+ credit card numbers, and similar values in the first place.
60
109
 
61
- When sensitive values can reach the logs indirectly, redact them. A global `on_log`
62
- subscriber runs inline, once per log event, before the event is handed to any appender,
63
- so it can scrub the message or payload for every destination:
110
+ When sensitive values can still reach the logs, for example in request headers or parameters that
111
+ are logged as they are, name the sensitive keys once. The value of every matching key is replaced
112
+ with `[FILTERED]` in every log entry, before any appender writes it:
64
113
 
65
114
  ~~~ruby
66
- SECRET_KEYS = %i[password token authorization secret].freeze
115
+ SemanticLogger.sensitive_keys = %i[passw secret token _key authorization cookie]
116
+ ~~~
67
117
 
68
- SemanticLogger.on_log do |log|
69
- log.payload&.each_key do |key|
70
- log.payload[key] = "[REDACTED]" if SECRET_KEYS.include?(key)
71
- end
72
- end
118
+ ~~~ruby
119
+ logger.info("Calling API", headers: {"Authorization" => "Bearer abc123", "Accept" => "application/json"})
120
+ # Written with: headers: {"Authorization" => "[FILTERED]", "Accept" => "application/json"}
121
+ ~~~
122
+
123
+ Rails applications that use [rails_semantic_logger](https://github.com/reidmorrison/rails_semantic_logger)
124
+ get this from `config.filter_parameters`; see [With Rails](#with-rails) below.
125
+
126
+ #### Naming the sensitive keys
127
+
128
+ | Value | Sensitive keys |
129
+ |-------|----------------|
130
+ | An Array | Each Symbol or String matches any key whose name contains it, ignoring case, as in Rails' `config.filter_parameters`. Each Regexp matches as written. |
131
+ | A Regexp | Keys whose names it matches. |
132
+ | An `ActiveSupport::ParameterFilter` | Keys for which `filter_param(name, nil)` returns a value, which replaces the key's value, so a custom `mask:` is kept. Any object that responds to `#filter_param` works the same way. |
133
+ | A Proc, or any object that responds to `#call` | Keys for which it returns true, given the key's name. |
134
+ | `nil` | None: nothing is redacted. The default. |
135
+
136
+ Keys are matched by name: the name of a Symbol key or a String key, both as written and in
137
+ snake_case, which is lower case. So `:_key` above also matches `"X-Api-Key"` as `"x_api_key"`,
138
+ `"apiKey"` and `"APIKey"` as `"api_key"`, and `"HTTP_X_API_KEY"` as `"http_x_api_key"`.
139
+
140
+ Like the default `filter_parameters` of Rails, a name matches wherever it appears in a key, so it
141
+ also matches some keys that are not secret: `:token` matches `max_tokens`, and `:_key` matches
142
+ `cache_key`. To match whole words only, use a Regexp:
143
+
144
+ ~~~ruby
145
+ SemanticLogger.sensitive_keys = [
146
+ # Anywhere in the key.
147
+ :passw, :secret, :token, :_key, :credential, :authorization, :cookie, :crypt, :certificate,
148
+ # Only as a whole word, so that "otp" does not match "footprint", nor "ssn" "business_name".
149
+ /(?<![a-z])(?:auth|pwd|otp|ssn|salt|cvv|cvc)(?![a-z])/
150
+ ]
151
+ ~~~
152
+
153
+ The keys are read when they are assigned, so adding to the Array afterwards has no effect: assign
154
+ the whole list again. The answer for each key name is remembered, so a Proc or object must always
155
+ give the same answer for the same name. It is called on the thread that writes the entries, so it
156
+ must be thread safe.
157
+
158
+ #### What is redacted
159
+
160
+ The payload, the named tags, the context that `on_log` subscribers add with `log.set_context`, and
161
+ metric dimensions, at any depth: inside each Hash, including a key that is itself a Hash, and inside
162
+ each Array, Set, Struct, Data, OpenStruct, and `ActionController::Parameters`. The value of a
163
+ sensitive key is replaced whole, even when it is a Hash. A Struct, Data, or OpenStruct that holds a
164
+ sensitive key is written as a Hash, and a Set as an Array, as the JSON formatters write them. A
165
+ structure that holds itself is cut off with `[FILTERED: circular]`, and one nested more than 32
166
+ levels deep is replaced with `[FILTERED: nested too deeply]`.
167
+
168
+ The application's own Hashes are never changed: the entry is given a copy, and only when it holds a
169
+ sensitive key, or a structure that holds itself or is nested too deeply. Other entries are written
170
+ as they are.
171
+
172
+ These are written as they are, so keep secrets out of them:
173
+
174
+ * The message, and a value other than a Hash passed after it, such as `logger.info("Login", user)`,
175
+ which is added to the message: pass it as `payload: user` instead.
176
+ * The tags, the message of the exception, and those of the exceptions that caused it.
177
+ * Any other object, which is written the way the formatter writes it. For some objects that
178
+ includes all of their attributes: for example a JSON formatter writes an Active Record model with
179
+ `as_json`. Log a Hash of the values you need instead.
180
+
181
+ To change text in messages, rewrite the message in a logger's `filter` or in an `on_log` subscriber;
182
+ see [Filtering](config.html#filtering). Do not redact in an appender's `filter`: every appender writes
183
+ the same log entry, so that only protects the appenders added after it, while the ones added before
184
+ it have already written the secret.
185
+
186
+ #### When it runs
187
+
188
+ Each entry is redacted once, on the thread that writes entries to the appenders (the background
189
+ thread, or with [synchronous logging](operations.html#synchronous-operation) the thread that logs),
190
+ before any appender writes it or its `filter` reads it. That includes the appenders that send
191
+ entries to error services, such as Sentry, Bugsnag, and Honeybadger, and appenders of your own. It
192
+ costs a few microseconds for a typical payload, off the application's own threads.
193
+
194
+ `on_log` subscribers and logger filters run earlier, on the thread that logs the entry, and receive it
195
+ as it was logged. The [Rollbar](appenders.html#rollbar) integration is one: it sends `log.to_h`, so
196
+ its entries are not redacted. So do the [testing helpers](testing.html), which capture entries as they
197
+ were logged.
198
+
199
+ When an entry cannot be redacted, for example because a Proc raises an error, the field is replaced
200
+ with `{redaction_failed: "ErrorClass"}`, never written as it is. The error's class, and where it was
201
+ raised, are reported to the internal logger, but not its message, which could hold the value.
202
+
203
+ #### With Rails
204
+
205
+ [rails_semantic_logger](https://github.com/reidmorrison/rails_semantic_logger) sets
206
+ `SemanticLogger.sensitive_keys` from `config.filter_parameters` once the application has initialized,
207
+ so that the keys Rails filters out of request parameters are filtered out of every log entry. To
208
+ turn it off:
209
+
210
+ ~~~ruby
211
+ config.rails_semantic_logger.redact_filter_parameters = false
73
212
  ~~~
74
213
 
75
- Redaction can also be applied to a single logger or appender with a `filter` that
76
- mutates the log and returns `true`. See [Filtering](config.html#filtering) for examples.
214
+ To use other keys instead, set them in `config/application.rb`, and they are kept:
77
215
 
78
- Rails applications should use the sister gem
79
- [rails_semantic_logger](https://github.com/reidmorrison/rails_semantic_logger), which
80
- honours `config.filter_parameters` so that parameters Rails already considers sensitive
81
- are filtered out of the logs.
216
+ ~~~ruby
217
+ config.semantic_logger.sensitive_keys = %i[passw secret token _key authorization cookie]
218
+ ~~~
219
+
220
+ Setting `config.semantic_logger.sensitive_keys = nil` does not turn it off, since that cannot be told
221
+ apart from never setting it; use `redact_filter_parameters = false`.
222
+
223
+ Notes:
224
+
225
+ * The default list of a new Rails application, in `config/initializers/filter_parameter_logging.rb`,
226
+ does not match the `Authorization` or `Cookie` header. Add them:
227
+ `Rails.application.config.filter_parameters += %i[authorization cookie]`.
228
+ * That list includes `:email`, so an email address is filtered, including the `user_email` named tag
229
+ that the [Sentry](appenders.html#sentry) appender sends as the user's email. It also matches keys
230
+ that are not secret, such as `max_tokens` (`:token`) and `cache_key` (`:_key`).
231
+ * A Proc in the list is left out, since it changes a value rather than naming a key. A dotted
232
+ filter, such as `"credit_card.code"`, only matches a key with that whole name, not `code` inside
233
+ `credit_card`.
234
+ * Active Job `arguments` and Action Mailer `args` are logged as JSON text, which is not redacted. For
235
+ a job that takes a secret, leave its arguments out of the log with `self.log_arguments = false`.
236
+ * Entries logged while the application starts, before the list is complete, may not be redacted.
237
+
238
+ To set it yourself, for example without rails_semantic_logger, do the same once the application has
239
+ initialized:
240
+
241
+ ~~~ruby
242
+ Rails.application.config.after_initialize do
243
+ filters = Rails.application.config.filter_parameters.reject { |filter| filter.respond_to?(:call) }
244
+ SemanticLogger.sensitive_keys = ActiveSupport::ParameterFilter.new(filters)
245
+ end
246
+ ~~~
82
247
 
83
248
  ### Transport encryption
84
249
 
85
250
  Appenders that send logs over the network support TLS. The appenders built on the
86
- `:http` appender (`:http`, `:splunk_http`, and `:elasticsearch_http`) default to
251
+ `:http` appender (`:http`, `:splunk_http`, `:elasticsearch_http`, and `:loki`) default to
87
252
  verifying the server certificate (`OpenSSL::SSL::VERIFY_PEER`) when an `https` URL is
88
- used.
253
+ used. The `:tcp` appender, and the `:syslog` appender over TCP, verify both the certificate
254
+ and the host name when `ssl:` is enabled.
255
+
256
+ The deprecated `:splunk` appender is the exception: its `splunk-sdk-ruby` gem never verifies
257
+ the certificate. Use `:splunk_http` instead.
89
258
 
90
- Do not disable certificate verification in production. Settings such as
259
+ Do not disable certificate verification. Settings such as
91
260
  `ssl: {verify_mode: OpenSSL::SSL::VERIFY_NONE}` expose the connection to
92
- man-in-the-middle attacks and should be limited to local development against
93
- self-signed certificates.
261
+ man-in-the-middle attacks. To connect to a server with a self-signed certificate, or one issued
262
+ by a private certificate authority, trust that certificate instead, for example with
263
+ `ssl: {ca_file: "/path/to/ca.pem"}`.
264
+
265
+ Credentials can be supplied in the url of the HTTP based appenders, for example
266
+ `https://user:password@host`, or as a query parameter. They are removed from the url
267
+ written to the internal logger when the server rejects a request, and from the error raised
268
+ for an invalid url. `#inspect` on any appender, for example when `SemanticLogger.appenders` is
269
+ printed in a console, shows only what that appender says is safe, such as its url without
270
+ credentials, and none of its passwords, tokens, keys, or client options.
94
271
 
95
272
  ### Log file permissions
96
273
 
@@ -104,9 +281,27 @@ an existing log file:
104
281
  SemanticLogger.add_appender(file_name: "production.log", permissions: 0o640)
105
282
  ~~~
106
283
 
284
+ With `permissions`, the log file is opened without following a symbolic link at its name, so a
285
+ link planted in the log directory can neither create nor open the file it points at. The file must
286
+ be a regular file owned by the process, with a single hard link, that the file name still names
287
+ once it is open. Otherwise, or when the file cannot be opened, nothing is written to it:
288
+ `add_appender` raises `IOError` giving the reason, with the error from opening the file, if any, as
289
+ its `cause`. When a file only fails the check once it is reopened later, on a rotation or after a
290
+ fork, the appender reports the reason once for each file, drops the log messages instead of
291
+ raising, and tries the file again every few seconds and at the next scheduled reopen, so that
292
+ logging resumes once the file is fixed. A symbolic link, hard link, or file planted in a shared log
293
+ directory, for example under the name of tomorrow's log file, can therefore neither loosen the
294
+ permissions of another file nor receive the log messages. A FIFO planted there fails to open
295
+ instead of blocking the process.
296
+
297
+ Without `permissions`, the file appender opens the log file the way Ruby's own `Logger` does,
298
+ following symbolic links, so that a log file can for example be linked to `/dev/stdout`. Keep the
299
+ log directory writable only by the application.
300
+
107
301
  ### Dependencies and supply chain
108
302
 
109
- Semantic Logger has a single runtime dependency, `concurrent-ruby`. Appenders for
303
+ Semantic Logger has two runtime dependencies, `concurrent-ruby` and `logger` (part of
304
+ Ruby's standard library until Ruby 4.0 moved it to the bundled gems). Appenders for
110
305
  third-party services (Kafka, MongoDB, Sentry, etc.) keep their backing gem optional: it
111
306
  is required lazily inside the appender only when that appender is used, and is never
112
307
  added to the gemspec. This keeps the dependency surface of an application that only uses
data/docs/testing.md CHANGED
@@ -1,9 +1,11 @@
1
1
  ---
2
2
  layout: default
3
+ title: Testing
4
+ description: >-
5
+ Assert that your code logged the expected message, level, payload or metric,
6
+ using the capture helpers for Minitest, RSpec, and other test frameworks.
3
7
  ---
4
8
 
5
- ## Testing
6
- {:.no_toc}
7
9
 
8
10
  **Contents**
9
11
 
@@ -50,6 +52,16 @@ messages = semantic_logger_events(ApiClient) do
50
52
  end
51
53
  ~~~
52
54
 
55
+ Passing a class replaces that class's `logger` while the block runs, so it captures only the log calls
56
+ made through that logger. Capture without a class instead when:
57
+
58
+ - the code under test logs through a logger it got some other way, such as `SemanticLogger["Name"]`
59
+ or a logger handed to it by a framework;
60
+ - an instance of the class called `logger` before the block, since each instance keeps the first
61
+ logger it is given; or
62
+ - you need to assert on `name`: events captured through a class are named
63
+ `SemanticLogger::Test::CaptureLogEvents`, not after the class.
64
+
53
65
  ### Step 3: assert on the events
54
66
 
55
67
  Check how many events were produced, then assert on each one with `assert_semantic_logger_event`:
@@ -106,7 +118,8 @@ test. The available checks are:
106
118
  | `time` | When the entry was created. |
107
119
  | `duration` | Duration of a measure call, in milliseconds. |
108
120
  | `backtrace` | The captured backtrace, if any. |
109
- | `thread_name` | Name of the thread that logged the entry. |
121
+ | `call_site` | Where the entry was logged, a `SemanticLogger::CallSite`, when `SemanticLogger.call_site_level` is set. |
122
+ | `thread_name` | Name of the thread that logged the entry, or its object id when the thread has no name. |
110
123
 
111
124
  ### Match part of a message or payload
112
125
 
@@ -183,6 +196,18 @@ events = capture_semantic_logger_events(ApiClient) do
183
196
  end
184
197
  ~~~
185
198
 
199
+ Passing a class replaces that class's `logger` until the end of the example, not just the block, so
200
+ it captures only the log calls made through that logger. Log calls made after the block are added to
201
+ the same returned array, so check the event count before running more code that logs. Capture without
202
+ a class instead when:
203
+
204
+ - the code under test logs through a logger it got some other way, such as `SemanticLogger["Name"]`
205
+ or a logger handed to it by a framework;
206
+ - an instance of the class called `logger` before the block, since each instance keeps the first
207
+ logger it is given; or
208
+ - you need to assert on `name`: events captured through a class are named
209
+ `SemanticLogger::Test::CaptureLogEvents`, not after the class.
210
+
186
211
  ### Step 3: assert on the events
187
212
 
188
213
  Use `be_a_semantic_logger_event` to assert on a single captured event: