semantic_logger 5.3.0 → 5.4.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bfb8a2265081eac50cc50aa7044a5d51b277fba016cb11eb76166d0c9216fe2b
4
- data.tar.gz: 678e62939127794a93e02280e9e0ed898af39a6015118bdba1f652a65abc4a2f
3
+ metadata.gz: 7fdc67c52e2d42e1a0fbc4a01db0304411d22ea229ef186645085cfe30091288
4
+ data.tar.gz: 6775421d2bf3ecef4015a8d298645f19c7da624f38bd6a9e9757262b5bc0868b
5
5
  SHA512:
6
- metadata.gz: a32ccdf8c3801b3e5166c6d3be83d9c8423defbd2b65e50dc11c262f7cab8c1b0b864a19e90ba9415f2e66d0548a45c0979cb42a03e93252f1381c87634289bc
7
- data.tar.gz: adab42f9b9e25495ea3a9b99c3322a30a95e4e7eb767f85d27a147831f30861053f08fe22d33318b77c805bf70d301e6c2adcff869cf4ea002607140b68c5ea8
6
+ metadata.gz: 72ac78355dfbb356c4e22cde3428687bbf5605402b81c0ff9ebf0fa9e081cd486bcb4f179c25efbbe8f685ac2aa05564013746283575ee7d16f1d9e0638e4a72
7
+ data.tar.gz: c41b1f0932e9c4d66daa75340115785b61eec111ba3fc167356517cf2071eb71db5db338ffec1162acd52e815295e512039d0d5bd24a2026ff294b9b8a677230
data/README.md CHANGED
@@ -99,7 +99,7 @@ and are therefore not automatically included by this gem:
99
99
  - NewRelicLogs Appender: gem 'newrelic_rpm'
100
100
  - Syslog Appender to a local syslog daemon: gem 'syslog' (a bundled gem since Ruby 3.4)
101
101
  - Syslog Appender to a remote syslog server over TCP or UDP: gem 'syslog_protocol' 0.9.2 or above
102
- - Syslog Appender to a remote syslog server over TCP: gem 'net_tcp_client'
102
+ - TCP Appender, and Syslog Appender to a remote syslog server over TCP: gem 'net_tcp_client' 2.3 or above
103
103
  - Splunk Appender (deprecated, use the Splunk HTTP appender): gem 'splunk-sdk-ruby'
104
104
  - Elasticsearch Appender: gem 'elasticsearch'
105
105
  - OpenSearch Appender: gem 'opensearch-ruby'
data/docs/api.md CHANGED
@@ -129,8 +129,8 @@ logger.info? # => true when :info and above are being logged
129
129
 
130
130
  ## Step 3: Add structured data
131
131
 
132
- This is what sets Semantic Logger apart. Instead of building a sentence by hand, pass the data as a
133
- Hash "payload" after the message:
132
+ This is what sets Semantic Logger apart. Instead of building a sentence by hand, pass the data as
133
+ keyword arguments after the message:
134
134
 
135
135
  ~~~ruby
136
136
  # Traditional logging bakes the data into a string:
@@ -145,6 +145,16 @@ Elasticsearch appender indexes `duration`, `result`, and `table` as real fields,
145
145
  and build dashboards on them without parsing log text. The fields that make up an entry are listed in
146
146
  [Log Event](log.html).
147
147
 
148
+ A few names are log arguments rather than payload fields: `duration` above sets the entry's duration,
149
+ and so do `message`, `exception`, `backtrace`, `call_site`, `min_duration`, `log_exception`,
150
+ `on_exception_level`, `metric`, `metric_amount`, and `dimensions` for what their names say. To log a
151
+ Hash that your code did not write out itself, such as request parameters or a parsed JSON body, pass
152
+ it as `payload:`, so that none of its keys can be taken for one of those arguments:
153
+
154
+ ~~~ruby
155
+ logger.info("Webhook received", payload: JSON.parse(body), account_id: account.id)
156
+ ~~~
157
+
148
158
  ## Step 4: Log an exception
149
159
 
150
160
  Pass a Ruby exception as the second argument. Its class, message, and backtrace are all captured:
@@ -157,10 +167,10 @@ rescue => exception
157
167
  end
158
168
  ~~~
159
169
 
160
- To log a payload and an exception together, pass both:
170
+ To log a payload and an exception together, pass the exception as `exception:`:
161
171
 
162
172
  ~~~ruby
163
- logger.error("Outbound call failed", {result: :failed}, exception)
173
+ logger.error("Outbound call failed", exception: exception, result: :failed)
164
174
  ~~~
165
175
 
166
176
  ## Step 5: Skip expensive messages with a block
@@ -175,19 +185,21 @@ logger.debug { "Processed #{records.sum(&:size)} bytes across #{records.size} re
175
185
 
176
186
  ### The full call signature
177
187
 
178
- Putting the pieces together, every level method accepts:
188
+ Putting the pieces together, every level method accepts either of these forms:
179
189
 
180
190
  ~~~ruby
181
- logger.info(message, payload_or_exception = nil, exception = nil, &block)
191
+ logger.info(message, exception, &block)
192
+ logger.info(message, field: value, ..., &block)
182
193
  ~~~
183
194
 
184
195
  - `message`: the text message. Optional only when a block is supplied.
185
- - `payload_or_exception`: an optional Hash payload, or a Ruby exception.
186
- - `exception`: an optional exception, used when you are also passing a payload.
187
- - `&block`: evaluated only when the level is active; its return value becomes the message.
196
+ - `exception`: a Ruby exception. To log fields along with it, pass it as `exception:` instead.
197
+ - `field: value, ...`: the payload fields, written out as keyword arguments, and the log arguments
198
+ described below, such as `exception:`, `duration:`, `metric:`, and `payload:`.
199
+ - `&block`: evaluated only when the level is active. A String it returns is added to the message,
200
+ and a Hash it returns is merged in as fields, as shown below.
188
201
 
189
- The same call can also be written as a single Hash, which is handy when assembling fields
190
- programmatically:
202
+ The message can also be passed as `message:`, so that the whole call is keyword arguments:
191
203
 
192
204
  ~~~ruby
193
205
  logger.debug(message: "Calling Supplier", payload: {request: "update", user: "Jack"})
@@ -209,15 +221,21 @@ logger.debug(message: "Order Load", duration: 0.4, call_site: query_location)
209
221
  logger.info(message: "Started GET /orders", call_site: false)
210
222
  ~~~
211
223
 
212
- In both forms, a key such as `duration` or `exception` is only used as an argument when its value is
213
- valid for it; otherwise it is logged as part of the payload. Any other keys supplied alongside
214
- `payload:` are merged into it, without overwriting its own values. When the Hash holds untrusted
215
- data, see [Logging untrusted hashes](security.html#logging-untrusted-hashes).
224
+ A key such as `duration` or `backtrace` is only used as an argument when its value is valid for it;
225
+ otherwise it is logged as part of the payload. `message`, `exception`, and `metric` take any value:
226
+ an `exception:` that is not an Exception is logged as an `ArgumentError` naming it. Any other keys supplied alongside `payload:` are
227
+ merged into it, and win over its values of the same name. Data your code did not write out itself
228
+ always goes in `payload:`; see [Logging untrusted hashes](security.html#logging-untrusted-hashes).
216
229
 
217
- A block can return the same Hash, but it never replaces an argument the entry already has. That
218
- includes the backtrace that an entry captures when its level is at or above
230
+ A block can return the same keys as a Hash, but it never replaces an argument the entry already has.
231
+ That includes the backtrace that an entry captures when its level is at or above
219
232
  `SemanticLogger.backtrace_level`, so to attach a backtrace of your own, pass `backtrace:` with the
220
- call rather than returning it from the block.
233
+ call rather than returning it from the block. A block that returns data, such as a parsed response
234
+ body, returns it as `payload:`:
235
+
236
+ ~~~ruby
237
+ logger.debug("Supplier replied") { {payload: JSON.parse(response.body)} }
238
+ ~~~
221
239
 
222
240
  ## Step 6: Measure how long something takes
223
241
 
@@ -297,7 +315,7 @@ Either a block or `:duration` must be supplied on every measure call.
297
315
 
298
316
  ### All measure options
299
317
 
300
- The second argument to a measure call is a Hash of options:
318
+ A measure call takes these keyword options after the message:
301
319
 
302
320
  - `:min_duration` [Float]: only log if the block takes longer than this many milliseconds. Default
303
321
  `0.0` (always log).
@@ -324,7 +342,7 @@ The second argument to a measure call is a Hash of options:
324
342
  [Recording where each entry was logged](config.html#recording-where-each-entry-was-logged).
325
343
 
326
344
  An option with a value that is not valid for it, such as a non-numeric `:min_duration` or an unknown
327
- level, is ignored and its default is used. Other keys in the Hash are not logged; pass the data to
345
+ level, is ignored and its default is used. Other keys are not logged; pass the data to
328
346
  log as `:payload`.
329
347
 
330
348
  Putting several together:
data/docs/appenders.md CHANGED
@@ -91,9 +91,9 @@ time the appender is used, and is never a hard dependency of Semantic Logger its
91
91
  | Destination | `add_appender` argument | Gem |
92
92
  |-------------|-------------------------|-----|
93
93
  | [HTTP(S)](#https) | `appender: :http` | |
94
- | [TCP (+SSL)](#tcp-appender-ssl) | `appender: :tcp` | `net_tcp_client` |
94
+ | [TCP (+SSL)](#tcp-appender-ssl) | `appender: :tcp` | `net_tcp_client` 2.3 or above |
95
95
  | [UDP](#udp-appender) | `appender: :udp` | |
96
- | [Syslog](#syslog) | `appender: :syslog` | `syslog` (local, Ruby 3.4+), `syslog_protocol` (remote), `net_tcp_client` (TCP) |
96
+ | [Syslog](#syslog) | `appender: :syslog` | `syslog` (local, Ruby 3.4+), `syslog_protocol` (remote), `net_tcp_client` 2.3 or above (TCP) |
97
97
 
98
98
  **Centralized logging and log aggregators**
99
99
 
@@ -108,9 +108,9 @@ time the appender is used, and is never a hard dependency of Semantic Logger its
108
108
  | [CloudWatch Logs](#cloudwatch-logs) | `appender: :cloudwatch_logs` | `aws-sdk-cloudwatchlogs` |
109
109
  | [OpenTelemetry](#opentelemetry) | `appender: :open_telemetry` | `opentelemetry-logs-sdk` |
110
110
  | [Logstash](#logstash) | `logger:` | `logstash-logger` |
111
- | [logentries.com](#logentriescom) | `appender: :tcp` | `net_tcp_client` |
111
+ | [logentries.com](#logentriescom) | `appender: :tcp` | `net_tcp_client` 2.3 or above |
112
112
  | [loggly.com](#logglycom) | `appender: :http` | |
113
- | [Papertrail](#papertrail) | `appender: :syslog` | `syslog_protocol`, `net_tcp_client` |
113
+ | [Papertrail](#papertrail) | `appender: :syslog` | `syslog_protocol`, `net_tcp_client` 2.3 or above |
114
114
 
115
115
  **Error and exception monitoring**
116
116
 
@@ -607,13 +607,23 @@ others or retrying.
607
607
 
608
608
  Net::TCPClient retries only after a network error, such as a refused, reset, or timed-out
609
609
  connection: it connects again up to `connect_retry_count:` times (default 10), and writes an entry
610
- again on a new connection up to `retry_count:` times (default 3). A write timeout, or an SSL error
611
- such as a certificate that does not verify, fails without a retry. The appender passes these and its
610
+ again on a new connection up to `retry_count:` times (default 3), all on the appender's worker
611
+ thread. A write timeout, or an SSL error such as a certificate that does not verify, fails without
612
+ a retry. To have the appender's back-off retry instead, as v6 does, pass `connect_retry_count: 0`
613
+ and `retry_count: 0`, which v6 also takes. The appender passes these and its
612
614
  other connection options, such as `connect_timeout:`, `write_timeout:`, and `ssl:`, to
613
615
  `Net::TCPClient.new`, which raises `ArgumentError` for a keyword it does not take; see
614
616
  [`Net::TCPClient#initialize`](https://github.com/reidmorrison/net_tcp_client/blob/master/lib/net/tcp_client/tcp_client.rb)
615
617
  for them all and their defaults.
616
618
 
619
+ v6 connects with a connection class of its own instead of Net::TCPClient, and takes only `server:`,
620
+ `servers:`, `policy:` (`:ordered` or `:random`), `connect_timeout:`, `write_timeout:`, `keepalive:`,
621
+ and `ssl:`, plus `connect_retry_count: 0`, `retry_count: 0`, and `buffered: false`, which are what
622
+ it does. So the other options and values report a
623
+ [deprecation warning](upgrading.html#seeing-deprecation-warnings), as do the same ones in the
624
+ `tcp_client:` Hash of the `:syslog` appender, where `server:` and `servers:` are deprecated too,
625
+ since v6 connects to the server of its `url:`.
626
+
617
627
  The TCP and UDP appenders separate records with a newline, so they default to the JSON formatter,
618
628
  which escapes embedded newlines and is safe with untrusted data. If you switch to a text formatter
619
629
  such as `:default` or `:color`, enable `escape_control_chars` so a newline in the logged data cannot
@@ -674,7 +684,7 @@ Gemfile:
674
684
  SemanticLogger.add_appender(appender: :syslog)
675
685
  ~~~
676
686
 
677
- Log to a remote Syslog server over TCP (the `net_tcp_client` and `syslog_protocol` gems are required).
687
+ Log to a remote Syslog server over TCP (the `net_tcp_client` gem, 2.3 or above, and the `syslog_protocol` gem are required).
678
688
  The default packet size is 1024 bytes:
679
689
 
680
690
  ~~~ruby
data/docs/config.md CHANGED
@@ -767,7 +767,9 @@ in the `\uXXXX` form: the C1 control characters (U+0080 to U+009F), the line and
767
767
  separators (U+2028, U+2029), at which editors and some log viewers start a new line, and the
768
768
  bidirectional controls (U+202A to U+202E, U+2066 to U+2069), such as the right-to-left override that
769
769
  can make logged text read backwards. The option is **disabled by default** to preserve the existing
770
- human readable output:
770
+ human readable output. Without it, the `:one_line` formatter still removes line breaks (line feeds, carriage
771
+ returns, vertical tabs, form feeds, U+0085, U+2028, and U+2029), so each of its entries stays on one
772
+ line, but it writes the other control characters as supplied:
771
773
 
772
774
  ```ruby
773
775
  # Text appender that escapes control characters in untrusted data:
data/docs/operations.md CHANGED
@@ -356,7 +356,7 @@ batch that the destination fails is discarded, and counted as `failed`, rather t
356
356
  after a back-off. So is every message queued after that one, ahead of the flush or close, without
357
357
  being written: during an outage, each would take as long to fail as the first, such as up to the
358
358
  `open_timeout` (2 seconds by default) of an HTTP based appender whose server does not answer, or
359
- longer for an appender that retries on its own, such as `:tcp` with its `connect_retry_count`. Those
359
+ longer for an appender that retries on its own, such as `:tcp` without `connect_retry_count: 0`. Those
360
360
  failures do not count towards `async_max_retries`. Once the flush or close has run, the messages
361
361
  queued after it are written as usual. A flush still waits while the first message is tried, and
362
362
  while a destination that takes the messages writes every one of them.
data/docs/rails.md CHANGED
@@ -66,6 +66,88 @@ already does:
66
66
  * `rails_stdout_logging`
67
67
  * `rails_12factor`
68
68
 
69
+ #### An existing application: the install generator
70
+
71
+ An application that already configures Rails logging, or still sets the deprecated
72
+ `config.rails_semantic_logger` appender options, can let Rails Semantic Logger v5.4 or later
73
+ configure it:
74
+
75
+ bin/rails generate rails_semantic_logger:install
76
+
77
+ In `config/application.rb` and each `config/environments/*.rb`, the generator:
78
+
79
+ * Removes the logger settings that Rails Semantic Logger replaces or ignores, when set without a
80
+ condition: `config.logger`, `config.log_formatter`, the `if ENV["RAILS_LOG_TO_STDOUT"].present?`
81
+ block of Rails 6 and 7.0 when it holds only logger settings, and commented-out examples of another
82
+ logger, such as `Syslog::Logger`. One with a condition, or a `RAILS_LOG_TO_STDOUT` block that does
83
+ more, is left for you to move.
84
+ * Writes an explicit [appenders block](#configuring-where-logs-go-the-appenders-block) at the top of
85
+ each environment's settings, listing the appenders that Rails Semantic Logger was already
86
+ creating, so that nothing changes until you edit them.
87
+ * Carries the [deprecated options](#deprecated-configuration-options) (`format`, `ap_options`,
88
+ `filter`, `add_file_appender`, `console_logger`) and the appenders added with
89
+ `config.semantic_logger.add_appender` into that block, and removes them.
90
+
91
+ For a production application that set `config.rails_semantic_logger.format = :json`, it writes:
92
+
93
+ ~~~ruby
94
+ # config/environments/production.rb
95
+ Rails.application.configure do
96
+ # Where the logs go. Rails Semantic Logger creates exactly the appenders listed here, so change this
97
+ # block to send them elsewhere. ...
98
+ config.rails_semantic_logger.appenders do |appenders|
99
+ appenders.add(file_name: config.paths["log"].first, formatter: :json)
100
+ appenders.add_server(io: $stdout, formatter: :color)
101
+ appenders.add_console(io: $stderr, formatter: :color)
102
+
103
+ # Or, in a container (Docker, Kubernetes), replace the lines above with JSON on stdout, one line
104
+ # per entry, and no log file:
105
+ # appenders.add(io: $stdout, formatter: :json)
106
+ end
107
+
108
+ # ...
109
+ end
110
+ ~~~
111
+
112
+ `config.paths["log"].first` is the file Rails Semantic Logger wrote to by default,
113
+ `log/production.log` under the application's root. Since the block now lists every destination,
114
+ change it there: see [Common recipes](#common-recipes).
115
+
116
+ The generator writes no block where it cannot keep the same logging, and says why for each
117
+ environment and each setting it left in place:
118
+
119
+ * An environment that already declares its appenders gets no block, nor does any environment when
120
+ `config/application.rb` declares them. Their ignored logger settings are still removed.
121
+ * An environment that loads another one, such as a `staging.rb` that starts with
122
+ `require_relative "production"`, gets no block of its own: it gets the other one's.
123
+ * An environment is left unchanged when a block would override a setting that has to stay where it
124
+ is: a deprecated option or a screen appender inside a condition (`... if ENV["JSON"]`), an option
125
+ set to a computed value, a conditional or computed `config.colorize_logging`, or
126
+ `config.paths["log"]` set in that file. So is an environment that another one loads when the
127
+ loading file sets any deprecated appender option, adds an appender that writes to the screen,
128
+ declares its own appenders, sets `config.colorize_logging`, or sets `config.paths["log"]`, since
129
+ the block would apply to it too. Move such a setting into the block by hand, then run the
130
+ generator again.
131
+ * An environment is also left unchanged when its block would declare no appender at all (both
132
+ `add_file_appender` and `console_logger` false, and no appender added), which would bring back
133
+ the default appenders, or when its file has no `.configure do` block
134
+ (`Rails.application.configure` or `MyApp::Application.configure`).
135
+ * When any environment is left unchanged, or declares its own appenders, the deprecated options and
136
+ appenders of `config/application.rb` stay where they are, since they apply to that environment
137
+ too. Its deprecated options then keep every environment from taking a block.
138
+ * An appender whose arguments read a local variable, call a method of the file, or read `config`
139
+ stays in place, since the block goes at the top of the settings, where they may not exist yet.
140
+ When it writes to standard out or standard error, its environment is left unchanged, since the
141
+ block's screen appenders would repeat its output.
142
+
143
+ One change to expect: before, the default log file gave its formatter to every file and IO
144
+ appender (standard out, standard error) that the application added with
145
+ `config.semantic_logger.add_appender`. Listed in the block, such an appender keeps the formatter it
146
+ was given, or the default text formatter when it was given none.
147
+
148
+ Read the changes with `git diff` before you commit them. `bin/rails destroy rails_semantic_logger:install`
149
+ does nothing, since the generator cannot put back what it removed.
150
+
69
151
  ### Out of the box
70
152
 
71
153
  With no configuration at all, Rails Semantic Logger:
@@ -136,7 +218,9 @@ Semantic Logger default of plain text.
136
218
  > logger it normally adds under `rails server`, and the standard-error logger it normally adds in
137
219
  > `rails console`. The block becomes the single source of truth for every destination. So declare
138
220
  > what you want: `add` for an always-on destination (such as the file log), `add_server` for screen
139
- > output while serving, and `add_console` for the Rails console.
221
+ > output while serving, and `add_console` for the Rails console. The
222
+ > [install generator](#an-existing-application-the-install-generator) writes the block that
223
+ > reproduces the automatic appenders, for you to change.
140
224
 
141
225
  ### Step 1: a single log file
142
226
 
@@ -974,6 +1058,28 @@ After they initialize, Rails Semantic Logger replaces the loggers of these libra
974
1058
 
975
1059
  ---
976
1060
 
1061
+ ## Upgrading to v5.4
1062
+
1063
+ v5.4 needs no configuration changes.
1064
+
1065
+ ### The install generator moves an application off the deprecated options
1066
+
1067
+ `bin/rails generate rails_semantic_logger:install` replaces the
1068
+ [deprecated appender options](#deprecated-configuration-options), and the Rails logger settings
1069
+ that Rails Semantic Logger ignores, with an explicit appenders block in each environment. See
1070
+ [An existing application: the install generator](#an-existing-application-the-install-generator).
1071
+ The deprecation warnings of those options now name the generator, and are not emitted while
1072
+ `rails generate` runs, since it loads the application's configuration.
1073
+
1074
+ ### A declared log file has its directory created
1075
+
1076
+ A log file declared in `config.rails_semantic_logger.appenders`, such as
1077
+ `appenders.add(file_name: "log/json/production.log")`, has its directory created, as the default
1078
+ log file always had. Before, an `add` log file could not be opened, and Rails Semantic Logger fell
1079
+ back to logging to standard error at the `:warn` level (see
1080
+ [A log file that cannot be opened now fails at boot](#a-log-file-that-cannot-be-opened-now-fails-at-boot)),
1081
+ and an `add_server` or `add_console` one raised.
1082
+
977
1083
  ## Upgrading to v5.3
978
1084
 
979
1085
  v5.3 requires Semantic Logger v5.3; see [Upgrading to Semantic Logger v5.3](upgrading.html#upgrading-to-semantic-logger-v53)
@@ -1180,6 +1286,9 @@ and will be **removed in v6**. Each is replaced by the [appenders block](#config
1180
1286
  | `config.rails_semantic_logger.console_logger` | Declare (or omit) an `add_console` appender |
1181
1287
  | `config.rails_semantic_logger.add_file_appender` | Declare appenders in the block (doing so already replaces the default file appender) |
1182
1288
 
1289
+ From v5.4, `bin/rails generate rails_semantic_logger:install` makes these replacements for you. See
1290
+ [An existing application: the install generator](#an-existing-application-the-install-generator).
1291
+
1183
1292
  ### Silencing the warnings until you migrate
1184
1293
 
1185
1294
  The gem registers its deprecator with the application as
data/docs/security.md CHANGED
@@ -50,6 +50,12 @@ SemanticLogger.add_appender(file_name: "production.log", formatter: {default: {e
50
50
  See [Escaping Control Characters](config.html#escaping-control-characters) for
51
51
  details.
52
52
 
53
+ The `:one_line` formatter always removes line feeds, carriage returns, vertical tabs,
54
+ form feeds, and the Unicode line breaks U+0085, U+2028, and U+2029 from every text field,
55
+ so each entry stays on a single line and a newline cannot forge another entry. It still writes ANSI escape sequences and bidirectional controls
56
+ as supplied, so enable `escape_control_chars` with it too when its output may be
57
+ viewed in a terminal or log viewer.
58
+
53
59
  The record-framed network appenders are already safe by default:
54
60
 
55
61
  * The **TCP** and **UDP** appenders default to the JSON formatter.
@@ -71,6 +77,8 @@ Semantic Logger only uses such a key as an argument when its value is valid for
71
77
  `duration` must be a finite real number, `backtrace` an Array of Strings, and `on_exception_level` a
72
78
  valid level. Any other value stays in the payload as data, and a `nil` value is ignored, so an
73
79
  untrusted hash passed to a level method such as `info` can never make the logging call raise.
80
+ `message`, `exception`, and `metric` take any value, so untrusted data can still set them: an
81
+ `exception` that is not an Exception is logged as an `ArgumentError` naming it.
74
82
  A valid `backtrace` also sets where the entry is recorded as logged: its file name, line number, and,
75
83
  with [`call_site_level`](config.html#recording-where-each-entry-was-logged), its method. A
76
84
  `call_site` key can only leave out the recorded call site, with `false`: the values that set one are
@@ -88,12 +96,13 @@ Symbol key it spells:
88
96
  logger.info("Webhook received", payload: JSON.parse(body, symbolize_names: true), account_id: account.id)
89
97
  ~~~
90
98
 
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
99
+ The same goes for a logging block: return the untrusted data as `payload:`, as in
100
+ `logger.debug("Webhook received") { {payload: JSON.parse(body, symbolize_names: true)} }`.
101
+ A hash returned from a block is otherwise checked the same way as one passed with the call, and
102
+ never replaces a value the log call supplied. A key is only used as an argument when
94
103
  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
104
+ counts as none, and a backtrace captured at the `backtrace_level` counts as supplied. A `payload`
105
+ that is not a Hash, such as the Array that `JSON.parse` can return, is logged under a `payload` key. Every other key, including an argument the entry already has, is
97
106
  added to the payload without replacing the log call's values, and wins over the block's own
98
107
  `payload` values of the same name. The caller's own payload Hash is left unchanged.
99
108
 
data/docs/testing.md CHANGED
@@ -44,10 +44,10 @@ end
44
44
  ~~~
45
45
 
46
46
  By default it captures events from every class. To capture only the events from one class, pass that
47
- class:
47
+ class as `klass:`:
48
48
 
49
49
  ~~~ruby
50
- messages = semantic_logger_events(ApiClient) do
50
+ messages = semantic_logger_events(klass: ApiClient) do
51
51
  # Only ApiClient log events created during this block are captured.
52
52
  end
53
53
  ~~~
data/docs/upgrading.md CHANGED
@@ -3,7 +3,8 @@ layout: default
3
3
  title: Upgrading
4
4
  description: >-
5
5
  Version-by-version upgrade notes for Semantic Logger, from v4.0 through the
6
- v5.3 OpenTelemetry log record changes.
6
+ v5.4 deprecations of the TCP options that v6 does not take, the positional
7
+ class of semantic_logger_events, and the benchmark_* methods.
7
8
  ---
8
9
 
9
10
 
@@ -59,6 +60,74 @@ Warning.extend(SemanticLoggerDeprecations)
59
60
  Do not log them through Semantic Logger itself: a warning reported on its background thread would
60
61
  then wait on that thread's own queue, which can stop all logging while the queue is full.
61
62
 
63
+ ### Upgrading to Semantic Logger v5.4
64
+
65
+ #### Remove the TCP options that v6 does not take
66
+
67
+ The `:tcp` appender, and the `:syslog` appender over TCP, hand their connection options to
68
+ `Net::TCPClient` from the `net_tcp_client` gem. v6 connects with a class of its own instead, which
69
+ takes only `server:`, `servers:`, `policy:` (`:ordered` or `:random`), `connect_timeout:`,
70
+ `write_timeout:`, `keepalive:`, and `ssl:`, plus the values of the options below that are what it
71
+ does, and raises `ArgumentError` for any other. So the others now report a
72
+ [deprecation warning](#seeing-deprecation-warnings):
73
+
74
+ | Option | Instead |
75
+ |--------|---------|
76
+ | `connect_retry_count:`, `retry_count:` | Set it to `0`, which v6 also takes. v6 does not retry by itself: the appender writes the entry again after its back-off, see `async_max_retries:` in [Operations](operations.html). Do not just remove it on v5: Net::TCPClient would then retry up to 10 and 3 times, on the appender's worker thread. |
77
+ | `connect_retry_interval:` | Remove it, or keep it only with `connect_retry_count: 0`. |
78
+ | `buffered:` | Set it to `false`, which v6 also takes, or remove it. |
79
+ | `read_timeout:` | Remove it: the appenders never read. |
80
+ | `close_on_error:`, `on_connect:`, `proxy_server:` | Remove it. |
81
+ | `policy:` other than `:ordered` or `:random`, such as a Proc | Use `:ordered` or `:random`. |
82
+ | `server:` in the `tcp_client:` of `:syslog` | Remove it: it is ignored, since the `url:` gives the server. |
83
+ | `servers:` in the `tcp_client:` of `:syslog` | Give the server in the `url:`: `servers:` replaced the server of the url, and v6 always connects to the server of the url. |
84
+
85
+ ~~~ruby
86
+ # Before:
87
+ SemanticLogger.add_appender(appender: :tcp, server: "logs:3300", connect_retry_count: 5, retry_count: 2)
88
+
89
+ # After, with the same behaviour in v5.4 and v6:
90
+ SemanticLogger.add_appender(appender: :tcp, server: "logs:3300", connect_retry_count: 0, retry_count: 0)
91
+ ~~~
92
+
93
+ #### Pass the class to `semantic_logger_events` as `klass:`
94
+
95
+ The Minitest helper `semantic_logger_events` takes the class whose events to capture as the keyword
96
+ `klass:`. Passing it positionally still works, but is deprecated, and reports a
97
+ [deprecation warning](#seeing-deprecation-warnings), since v6 takes it only as `klass:`:
98
+
99
+ ~~~ruby
100
+ # Before:
101
+ messages = semantic_logger_events(ApiClient) { ApiClient.new.call }
102
+
103
+ # After:
104
+ messages = semantic_logger_events(klass: ApiClient) { ApiClient.new.call }
105
+ ~~~
106
+
107
+ The RSpec helper `capture_semantic_logger_events(ApiClient)` is unchanged.
108
+
109
+ #### Replace the `benchmark_*` methods with `measure_*`
110
+
111
+ The `benchmark_trace`, `benchmark_debug`, `benchmark_info`, `benchmark_warn`, `benchmark_error`,
112
+ `benchmark_fatal`, and `benchmark` methods of a logger are the old names of `measure_trace` through
113
+ `measure_fatal` and `measure`, which take the same arguments. They still work, but are deprecated,
114
+ and report a [deprecation warning](#seeing-deprecation-warnings), since v6 removes them:
115
+
116
+ ~~~ruby
117
+ # Before:
118
+ logger.benchmark_info("Called supplier") { supplier.call }
119
+
120
+ # After:
121
+ logger.measure_info("Called supplier") { supplier.call }
122
+ ~~~
123
+
124
+ Update the `net_tcp_client` gem to version 2.3 or later, which calls `measure_*`, if your application
125
+ uses it, such as for the `:tcp` appender or the `:syslog` appender over TCP: earlier versions call
126
+ `benchmark_debug` and `benchmark_error` at every connection and write. The `:tcp` appender, and the
127
+ `:syslog` appender over TCP, report a warning when they are added with such a version, saying to
128
+ update it, and keep those calls from warning; an application that uses `net_tcp_client` without them
129
+ gets the warning at each call.
130
+
62
131
  ### Upgrading to Semantic Logger v5.3
63
132
 
64
133
  #### OpenTelemetry log records
@@ -139,7 +139,9 @@ module SemanticLogger
139
139
  # Password for basic Authentication.
140
140
  #
141
141
  # header: [Hash]
142
- # Custom HTTP headers to send with each request.
142
+ # Custom HTTP headers to send with each request. Each one replaces the default header of the
143
+ # same name, compared in any case, such as "content-type" for Content-Type. A header set later
144
+ # through #header, or written to it directly by a subclass, is not compared in any case.
143
145
  # Default: {} ( do not send any custom headers)
144
146
  # Example: {"Authorization" => "Bearer BEARER_TOKEN"}
145
147
  #
@@ -215,8 +217,9 @@ module SemanticLogger
215
217
  "Content-Type" => "application/json",
216
218
  "Connection" => "keep-alive",
217
219
  "Keep-Alive" => "300"
218
- }.merge(header)
219
- @header["Content-Encoding"] = "gzip" if @compress
220
+ }
221
+ header&.each { |name, value| replace_header(name, value) }
222
+ replace_header("Content-Encoding", "gzip") if @compress
220
223
 
221
224
  uri = parse_url(@url)
222
225
  @server = uri.host
@@ -379,6 +382,15 @@ module SemanticLogger
379
382
 
380
383
  private
381
384
 
385
+ # Sets the header of that name, replacing one whose name differs from it only in case, since HTTP
386
+ # header names are case-insensitive: otherwise both would be kept, and Net::HTTP would send only
387
+ # one of them, reporting the other as duplicated under -W. The name is kept as given, a String or
388
+ # a Symbol.
389
+ def replace_header(name, value)
390
+ @header.delete_if { |existing, _value| existing.to_s.casecmp?(name.to_s) }
391
+ @header[name] = value
392
+ end
393
+
382
394
  # Returns [Net::HTTP] a new connection, not yet started, after making it the appender's. Records
383
395
  # the process that built it, which owns its connection (see #reopen).
384
396
  def build_http
@@ -46,8 +46,9 @@ module SemanticLogger
46
46
  # Default: 'loki/api/v1/push'
47
47
  #
48
48
  # header: [Hash]
49
- # HTTP headers to send with every request, such as X-Scope-OrgID, merged over the
50
- # headers of the HTTP appender, whose Content-Type is already application/json.
49
+ # HTTP headers to send with every request, such as X-Scope-OrgID, each replacing the header of
50
+ # the HTTP appender with the same name, compared in any case, whose Content-Type is already
51
+ # application/json.
51
52
  # Default: {'Content-Type' => 'application/json'}
52
53
  #
53
54
  # formatter: [Object|Proc|Symbol|Hash]
@@ -110,7 +110,7 @@ module SemanticLogger
110
110
  super(compress: compress, **args, &)
111
111
 
112
112
  # Put splunk auth token in the header of every HTTP post.
113
- @header["Authorization"] = "Splunk #{token}"
113
+ replace_header("Authorization", "Splunk #{token}")
114
114
  end
115
115
 
116
116
  # Returns [String] JSON to send to Splunk.
@@ -57,6 +57,9 @@ module SemanticLogger
57
57
  # Specify custom parameters to pass into Net::TCPClient.new
58
58
  # For a list of options see the net_tcp_client documentation:
59
59
  # https://github.com/reidmorrison/net_tcp_client/blob/master/lib/net/tcp_client/tcp_client.rb
60
+ # v6 takes only policy: (:ordered or :random), connect_timeout:, write_timeout:, keepalive:, and
61
+ # ssl:, plus connect_retry_count: 0, retry_count: 0, buffered: false, and connect_retry_interval:
62
+ # with connect_retry_count: 0, so the others report a deprecation warning (see TcpClientOptions).
60
63
  #
61
64
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
62
65
  # Override the log level for this appender.
@@ -141,7 +144,7 @@ module SemanticLogger
141
144
  @protocol = (uri.scheme || :syslog).to_sym
142
145
  @port = uri.port || 514
143
146
  @server = "localhost" if @protocol == :syslog
144
- @tcp_client_options = tcp_client
147
+ @tcp_client_options = tcp_client || {}
145
148
 
146
149
  raise "Unknown protocol #{@protocol}!" unless %i[syslog tcp udp].include?(@protocol)
147
150
 
@@ -175,6 +178,14 @@ module SemanticLogger
175
178
  end
176
179
 
177
180
  super(**args, &)
181
+ if @protocol == :tcp
182
+ TcpClientOptions.report_deprecated(
183
+ @tcp_client_options, ":syslog",
184
+ server: "it is ignored, since the url gives the server",
185
+ servers: "it replaces the server of the url, which v6 always connects to: give that server in the url"
186
+ )
187
+ logger.extend(TcpClientOptions::BenchmarkWithoutWarning) if TcpClientOptions.report_outdated_gem(":syslog")
188
+ end
178
189
  reopen
179
190
  end
180
191
 
@@ -25,14 +25,6 @@ module SemanticLogger
25
25
  # server: 'server:3300',
26
26
  # )
27
27
  #
28
- # Example, with connection retry options:
29
- # SemanticLogger.add_appender(
30
- # appender: :tcp,
31
- # server: 'server:3300',
32
- # connect_retry_interval: 0.1,
33
- # connect_retry_count: 5
34
- # )
35
- #
36
28
  # Example, with SSL enabled:
37
29
  # SemanticLogger.add_appender(
38
30
  # appender: :tcp,
@@ -49,9 +41,12 @@ module SemanticLogger
49
41
  # Net::TCPClient Parameters:
50
42
  # Every keyword argument other than the appender parameters below goes to Net::TCPClient.new,
51
43
  # which raises ArgumentError for a keyword it does not take. See Net::TCPClient#initialize for
52
- # them and their defaults, such as connect_timeout:, write_timeout:, connect_retry_count:,
53
- # retry_count:, policy:, and ssl:
44
+ # them and their defaults, such as connect_timeout:, write_timeout:, policy:, and ssl:
54
45
  # https://github.com/reidmorrison/net_tcp_client/blob/master/lib/net/tcp_client/tcp_client.rb
46
+ # v6 takes only server:, servers:, policy: (:ordered or :random), connect_timeout:, write_timeout:,
47
+ # keepalive:, and ssl:, plus connect_retry_count: 0, retry_count: 0, buffered: false, and
48
+ # connect_retry_interval: with connect_retry_count: 0, so the others report a deprecation warning (see
49
+ # TcpClientOptions).
55
50
  #
56
51
  # :server [String]
57
52
  # The server to connect to, as "host:port", such as 'localhost:2000' or '192.168.1.10:80'.
@@ -101,14 +96,6 @@ module SemanticLogger
101
96
  # appender: :tcp,
102
97
  # server: 'server:3300'
103
98
  # )
104
- #
105
- # Example, with connection retry options:
106
- # SemanticLogger.add_appender(
107
- # appender: :tcp,
108
- # server: 'server:3300',
109
- # connect_retry_interval: 0.1,
110
- # connect_retry_count: 5
111
- # )
112
99
  def initialize(separator: "\n",
113
100
  level: nil, formatter: nil, filter: nil, application: nil, environment: nil,
114
101
  host: nil, metrics: false, **tcp_client_args, &)
@@ -121,6 +108,8 @@ module SemanticLogger
121
108
 
122
109
  super(level: level, formatter: formatter, filter: filter, application: application,
123
110
  environment: environment, host: host, metrics: metrics, &)
111
+ TcpClientOptions.report_deprecated(tcp_client_args, ":tcp")
112
+ logger.extend(TcpClientOptions::BenchmarkWithoutWarning) if TcpClientOptions.report_outdated_gem(":tcp")
124
113
  reopen
125
114
  end
126
115
 
@@ -0,0 +1,88 @@
1
+ module SemanticLogger
2
+ module Appender
3
+ # The options of Net::TCPClient that the :tcp appender, and the :syslog appender in `tcp_client:`, hand to it,
4
+ # which v6 no longer takes, since it connects with a connection class of its own instead of net_tcp_client.
5
+ module TcpClientOptions
6
+ RETRIES = "v6 does not retry by itself, so it takes only connect_retry_count: 0 and retry_count: 0, which " \
7
+ "keep the worker thread from waiting on retries now too: the appender writes the entry again after " \
8
+ "its back-off instead, see async_max_retries:".freeze
9
+
10
+ # Each option that v6 refuses, with why, or what to use instead.
11
+ DEPRECATED = {
12
+ connect_retry_count: RETRIES,
13
+ connect_retry_interval: "#{RETRIES}, and takes connect_retry_interval: only with connect_retry_count: 0".freeze,
14
+ retry_count: RETRIES,
15
+ read_timeout: "the appender never reads",
16
+ buffered: "v6 writes each entry at once, so it takes only buffered: false",
17
+ close_on_error: "the connection is closed after any error",
18
+ on_connect: "it is not called",
19
+ proxy_server: "the appender does not connect through a proxy"
20
+ }.freeze
21
+
22
+ # The values of the deprecated options that v6 still takes, since they are what it does.
23
+ V6_VALUES = {connect_retry_count: 0, retry_count: 0, buffered: false}.freeze
24
+
25
+ # The policies that v6 keeps, of those that Net::TCPClient takes.
26
+ POLICIES = %i[ordered random].freeze
27
+
28
+ # Reports a deprecation warning that names each of the supplied options that v6 refuses, with why, as the
29
+ # options of the named appender, such as ":tcp". `refused` names other options that v6 refuses for this
30
+ # appender, with why, such as the server of the :syslog appender, which its url gives. An option given as nil
31
+ # is not reported, since v6 ignores it (Net::TCPClient takes nil as the value), nor is one given a value
32
+ # that v6 still takes (see V6_VALUES).
33
+ def self.report_deprecated(options, appender, refused = {})
34
+ reasons = DEPRECATED.merge(refused).reject { |name, _| options[name].nil? || v6_value?(name, options) }
35
+ policy = options[:policy]
36
+ unless policy.nil? || POLICIES.include?(policy)
37
+ reasons[:policy] = "it takes only :ordered or :random, not #{policy.is_a?(Proc) ? 'a Proc' : policy.inspect}"
38
+ end
39
+ return if reasons.empty?
40
+
41
+ Deprecation.warn(
42
+ "The #{appender} appender's #{reasons.keys.map { |name| "#{name}:" }.join(', ')} " \
43
+ "#{reasons.one? ? 'is' : 'are'} deprecated, and v6 raises ArgumentError for " \
44
+ "#{reasons.one? ? 'it' : 'them'}, since it no longer connects with net_tcp_client: " \
45
+ "#{reasons.map { |name, reason| "#{name}: #{reason}" }.join('; ')}."
46
+ )
47
+ end
48
+
49
+ # The first version of net_tcp_client that calls measure_* on its logger, rather than the deprecated
50
+ # benchmark_debug and benchmark_error.
51
+ MEASURE_VERSION = Gem::Version.new("2.3.0")
52
+
53
+ # The benchmark_* methods that net_tcp_client older than MEASURE_VERSION calls, without the deprecation warning
54
+ # of Base#benchmark_debug and the others. The :tcp and :syslog appenders extend their own internal logger with
55
+ # it, the one they give net_tcp_client, when .report_outdated_gem says it is outdated: it calls them at every
56
+ # connection and write, on the appender's worker thread, where a warning would name no line of the
57
+ # application, and would raise from each write where the application raises deprecation warnings, or log an
58
+ # entry for each write where it logs them.
59
+ module BenchmarkWithoutWarning
60
+ Levels::LEVELS.each do |level|
61
+ define_method(:"benchmark_#{level}") do |message, params = {}, &block|
62
+ public_send(:"measure_#{level}", message, params, &block)
63
+ end
64
+ end
65
+ end
66
+
67
+ # Returns whether the installed net_tcp_client is older than MEASURE_VERSION, after reporting a deprecation
68
+ # warning, as the named appender, such as ":tcp", is created, that says to update it.
69
+ def self.report_outdated_gem(appender, version = Net::TCPClient::VERSION)
70
+ return false unless Gem::Version.new(version) < MEASURE_VERSION
71
+
72
+ Deprecation.warn(
73
+ "The #{appender} appender uses net_tcp_client #{version}, which calls the deprecated benchmark_* methods " \
74
+ "at every connection and write. Update net_tcp_client to #{MEASURE_VERSION} or later, which calls measure_*."
75
+ )
76
+ true
77
+ end
78
+
79
+ # Whether the option has a value that v6 still takes, as the connect_retry_interval: of no connect retries.
80
+ def self.v6_value?(name, options)
81
+ return V6_VALUES[:connect_retry_count] == options[:connect_retry_count] if name == :connect_retry_interval
82
+
83
+ V6_VALUES.key?(name) && V6_VALUES[name] == options[name]
84
+ end
85
+ private_class_method :v6_value?
86
+ end
87
+ end
88
+ end
@@ -25,6 +25,7 @@ module SemanticLogger
25
25
  autoload :SplunkHttp, "semantic_logger/appender/splunk_http"
26
26
  autoload :Syslog, "semantic_logger/appender/syslog"
27
27
  autoload :Tcp, "semantic_logger/appender/tcp"
28
+ autoload :TcpClientOptions, "semantic_logger/appender/tcp_client_options"
28
29
  autoload :TextOutput, "semantic_logger/appender/text_output"
29
30
  autoload :Udp, "semantic_logger/appender/udp"
30
31
  autoload :Wrapper, "semantic_logger/appender/wrapper"
@@ -52,7 +52,8 @@ module SemanticLogger
52
52
  end
53
53
 
54
54
  # Implement the log level calls
55
- # logger.debug(message, hash|exception=nil, &block)
55
+ # logger.debug(message, exception=nil, &block)
56
+ # logger.debug(message, field: value, ..., &block)
56
57
  #
57
58
  # Implement the log level query
58
59
  # logger.debug?
@@ -66,11 +67,13 @@ module SemanticLogger
66
67
  #
67
68
  # payload
68
69
  # [Hash|Exception] Optional hash payload or an exception to be logged
70
+ # Its keys can also be log arguments (duration, metric, exception, ...), so a Hash
71
+ # the caller did not write out itself belongs in `payload:` (see docs/security.md).
69
72
  # Default: nil
70
73
  #
71
74
  # exception
72
75
  # [Exception] Optional exception to be logged
73
- # Allows both an exception and a payload to be logged
76
+ # Kept for compatibility: to log an exception with a payload, pass it as `exception:`
74
77
  # Default: nil
75
78
  #
76
79
  # Examples:
@@ -117,12 +120,12 @@ module SemanticLogger
117
120
  end
118
121
  end
119
122
 
123
+ # Deprecated: use measure_#{level}, which takes the same arguments. Removed in v6.
120
124
  def benchmark_#{level}(message, params = {}, &block)
121
- if level_index <= #{index}
122
- measure_internal(:#{level}, #{index}, message, params, &block)
123
- else
124
- block.call(params) if block
125
- end
125
+ SemanticLogger::Deprecation.warn(
126
+ "benchmark_#{level} is deprecated and removed in v6. Use measure_#{level}, which takes the same arguments."
127
+ )
128
+ measure_#{level}(message, params, &block)
126
129
  end
127
130
  METHODS
128
131
  end
@@ -137,8 +140,13 @@ module SemanticLogger
137
140
  end
138
141
  end
139
142
 
140
- # Backward compatibility
141
- alias benchmark measure
143
+ # Deprecated: use measure, which takes the same arguments. Removed in v6.
144
+ def benchmark(level, message, params = {}, &)
145
+ SemanticLogger::Deprecation.warn(
146
+ "benchmark is deprecated and removed in v6. Use measure, which takes the same arguments."
147
+ )
148
+ measure(level, message, params, &)
149
+ end
142
150
 
143
151
  # Log a thread backtrace
144
152
  def backtrace(thread: Thread.current,
@@ -6,6 +6,13 @@ module SemanticLogger
6
6
  alias debug trace
7
7
  alias debug? trace?
8
8
  alias measure_debug measure_trace
9
- alias benchmark_debug benchmark_trace
9
+
10
+ # Deprecated: use measure_debug, which takes the same arguments. Removed in v6.
11
+ def benchmark_debug(message, params = {}, &)
12
+ SemanticLogger::Deprecation.warn(
13
+ "benchmark_debug is deprecated and removed in v6. Use measure_debug, which takes the same arguments."
14
+ )
15
+ measure_trace(message, params, &)
16
+ end
10
17
  end
11
18
  end
@@ -4,8 +4,9 @@ module SemanticLogger
4
4
  #
5
5
  # Notes:
6
6
  # * Line breaks are stripped from every text field: the name, thread name, file name, tags,
7
- # named tags, message, payload and exception message. They are new lines and carriage
8
- # returns, and the Unicode next line (U+0085), line separator (U+2028), and paragraph
7
+ # named tags, message, payload and exception message. They are new lines, carriage returns,
8
+ # vertical tabs and form feeds (which most terminals move down a line for), and the Unicode
9
+ # next line (U+0085), line separator (U+2028), and paragraph
9
10
  # separator (U+2029), at which editors, browsers, and some log viewers also start a new line.
10
11
  # With `escape_control_chars: true` they are escaped instead, the Unicode ones in the
11
12
  # `\uXXXX` form, and so are the other control characters, as the other text formatters
@@ -18,12 +19,16 @@ module SemanticLogger
18
19
  # separator, and paragraph separator.
19
20
  UNICODE_LINE_BREAKS = "\u0085\u2028\u2029".freeze
20
21
 
22
+ # The ASCII line breaks: line feed, carriage return, vertical tab, and form feed, at which most
23
+ # terminals move down a line, as a String#delete character set.
24
+ ASCII_LINE_BREAKS = "\r\n\v\f".freeze
25
+
21
26
  # Every line break, as a String#delete character set.
22
- LINE_BREAKS = "\r\n#{UNICODE_LINE_BREAKS}".freeze
27
+ LINE_BREAKS = "#{ASCII_LINE_BREAKS}#{UNICODE_LINE_BREAKS}".freeze
23
28
 
24
- # A line break, with the white space around it, between two lines of exception details. A
25
- # carriage return before a line feed is part of that white space.
26
- DETAILS_LINE_BREAK = /\s*[\n#{UNICODE_LINE_BREAKS}]\s*/
29
+ # A line break, with the white space around it, between two lines of exception details. Any
30
+ # of LINE_BREAKS counts, so that one on its own, such as a form feed, still leaves a space.
31
+ DETAILS_LINE_BREAK = /\s*[#{LINE_BREAKS}]\s*/
27
32
 
28
33
  # Shortened before its line breaks are removed or escaped, as the other text formatters do
29
34
  # (see Default#shortened_thread_name), so that an escape is never cut in two.
@@ -106,8 +111,8 @@ module SemanticLogger
106
111
  text = Utils.encode_utf8_string(escape_control_characters(value.to_s))
107
112
  # #escape_control_characters has already escaped every line break.
108
113
  return text if escape_control_chars
109
- # Most text is ASCII, and deleting two characters is quicker than deleting five.
110
- return text.delete("\r\n") if text.ascii_only?
114
+ # Most text is ASCII, which only the ASCII line breaks need to be deleted from.
115
+ return text.delete(ASCII_LINE_BREAKS) if text.ascii_only?
111
116
 
112
117
  text.delete(LINE_BREAKS)
113
118
  end
@@ -88,10 +88,10 @@ module SemanticLogger
88
88
 
89
89
  super(url: url, formatter: formatter, **args, &)
90
90
 
91
- @header["X-SF-TOKEN"] = token
91
+ replace_header("X-SF-TOKEN", token)
92
92
  # Built from the parsed path, not the supplied url, so that a query string in the
93
93
  # url stays at the end of the request uri. See Appender::Http#uri_with_query.
94
- @full_path = "#{@path.end_with?('/') ? @path : "#{@path}/"}#{END_POINT}"
94
+ @full_path = "#{@path.end_with?('/') ? @path : "#{@path}/"}#{END_POINT}"
95
95
  end
96
96
 
97
97
  def log(log)
@@ -33,14 +33,14 @@ module SemanticLogger
33
33
 
34
34
  def after_test(test)
35
35
  if test.error?
36
- logger.benchmark_error("FAIL #{test.class.name} #{test.name}", duration: test.time * 1_000,
37
- metric: "minitest/fail")
36
+ logger.measure_error("FAIL #{test.class.name} #{test.name}", duration: test.time * 1_000,
37
+ metric: "minitest/fail")
38
38
  elsif test.skipped?
39
- logger.benchmark_warn("SKIP #{test.class.name} #{test.name}", duration: test.time * 1_000,
40
- metric: "minitest/skip")
39
+ logger.measure_warn("SKIP #{test.class.name} #{test.name}", duration: test.time * 1_000,
40
+ metric: "minitest/skip")
41
41
  else
42
- logger.benchmark_info("PASS #{test.class.name} #{test.name}", duration: test.time * 1_000,
43
- metric: "minitest/pass")
42
+ logger.measure_info("PASS #{test.class.name} #{test.name}", duration: test.time * 1_000,
43
+ metric: "minitest/pass")
44
44
  end
45
45
  end
46
46
  end
@@ -4,9 +4,18 @@ module SemanticLogger
4
4
  # Returns [Array<SemanticLogger::Log>] the log events from Semantic Logger
5
5
  # captured whilst executing the supplied block.
6
6
  #
7
+ # Pass `klass:` to capture only the log events of that class's logger. Passing the class
8
+ # positionally is deprecated, since v6 takes it only as `klass:`.
9
+ #
7
10
  # Notes:
8
11
  # - All log messages are returned regardless of the global default log level.
9
12
  def semantic_logger_events(deprecated_klass = nil, klass: deprecated_klass, silence: :trace, &block)
13
+ if deprecated_klass
14
+ SemanticLogger::Deprecation.warn(
15
+ "semantic_logger_events with the class as its argument is deprecated, and v6 takes it only as klass:. " \
16
+ "Pass the class as klass: instead."
17
+ )
18
+ end
10
19
  logger = SemanticLogger::Test::CaptureLogEvents.new
11
20
  if klass
12
21
  klass.stub(:logger, logger, &block)
@@ -1,3 +1,3 @@
1
1
  module SemanticLogger
2
- VERSION = "5.3.0".freeze
2
+ VERSION = "5.4.0".freeze
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: semantic_logger
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.3.0
4
+ version: 5.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Reid Morrison
@@ -87,6 +87,7 @@ files:
87
87
  - lib/semantic_logger/appender/splunk_http.rb
88
88
  - lib/semantic_logger/appender/syslog.rb
89
89
  - lib/semantic_logger/appender/tcp.rb
90
+ - lib/semantic_logger/appender/tcp_client_options.rb
90
91
  - lib/semantic_logger/appender/text_output.rb
91
92
  - lib/semantic_logger/appender/udp.rb
92
93
  - lib/semantic_logger/appender/wrapper.rb
@@ -161,7 +162,7 @@ metadata:
161
162
  bug_tracker_uri: https://github.com/reidmorrison/semantic_logger/issues
162
163
  changelog_uri: https://github.com/reidmorrison/semantic_logger/blob/main/CHANGELOG.md
163
164
  documentation_uri: https://logger.reidmorrison.com
164
- source_code_uri: https://github.com/reidmorrison/semantic_logger/tree/v5.3.0
165
+ source_code_uri: https://github.com/reidmorrison/semantic_logger/tree/v5.4.0
165
166
  rubygems_mfa_required: 'true'
166
167
  rdoc_options: []
167
168
  require_paths: