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
@@ -1,4 +1,6 @@
1
1
  require "json"
2
+ require "uri"
3
+ require "semantic_logger/core_ext/warning"
2
4
 
3
5
  module SemanticLogger
4
6
  # Internal-use only utility functions for Semantic Logger.
@@ -25,6 +27,68 @@ module SemanticLogger
25
27
  constant
26
28
  end
27
29
 
30
+ # Returns [URI] the parsed url, supplied as the named option.
31
+ #
32
+ # Raises URI::InvalidURIError for an invalid url, including nil, as .without_url_in_errors does.
33
+ def self.parse_url(url, option: ":url", hint: nil)
34
+ without_url_in_errors(option: option, hint: hint) { URI.parse(url) }
35
+ end
36
+
37
+ # Returns the result of the block, which uses the url supplied as the named option, for example
38
+ # to build a client gem's connection.
39
+ #
40
+ # Raises any of the errors from the block again, of the same class, without the url in its
41
+ # message, or as its cause, since a url can hold a user and password, or a token in its path or
42
+ # query string, and URI and client gems put the url in the error for an invalid one.
43
+ def self.without_url_in_errors(option: ":url", hint: nil, errors: [URI::InvalidURIError])
44
+ yield
45
+ rescue *errors => e
46
+ raise(e.class, ["Invalid #{option}, it is not a valid URI.", hint].compact.join(" "), cause: nil)
47
+ end
48
+
49
+ # Returns [String] the scheme, host, and any non-default port of the url, which is safe to log.
50
+ #
51
+ # Everything else is left out, since log services carry credentials in each part of a url: the
52
+ # user and password, the query string (for example a Datadog api key), and the path (for example
53
+ # the token at the end of a Sumo Logic HTTP source url). An invalid url is not shown at all.
54
+ def self.redacted_url(url)
55
+ uri = URI.parse(url.to_s)
56
+ port = uri.port == uri.default_port ? nil : uri.port
57
+ uri.class.build(scheme: uri.scheme, host: uri.host, port: port).to_s
58
+ rescue URI::Error
59
+ "(invalid url)"
60
+ end
61
+
62
+ # Returns the value, deep frozen so that code in any Ractor can read the constant or setting
63
+ # that holds it.
64
+ #
65
+ # copy: false freezes the value itself, so only use it for a value that Semantic Logger owns, such
66
+ # as one of its constants. A value this Ruby cannot share, such as an UnboundMethod before Ruby 4.0,
67
+ # is returned unshareable, and may be left partly frozen. On a Ruby without Ractors (JRuby) the
68
+ # value is returned as it is.
69
+ #
70
+ # copy: true leaves the supplied value as it is, and returns a deep frozen copy of it, for a value
71
+ # that belongs to someone else, such as a setting. Without Ractors, or for a value Ruby cannot
72
+ # copy, the copy is a shallow frozen dup.
73
+ def self.make_shareable(value, copy: false)
74
+ return copy ? frozen_dup(value) : value unless defined?(::Ractor)
75
+
76
+ begin
77
+ ::Ractor.make_shareable(value, copy: copy)
78
+ rescue ::Ractor::Error, TypeError
79
+ copy ? frozen_dup(value) : value
80
+ end
81
+ end
82
+
83
+ # Returns a frozen shallow copy of the value, the value when it is already frozen, or the value
84
+ # itself when it cannot be copied, such as a Thread.
85
+ def self.frozen_dup(value)
86
+ value.frozen? ? value : value.dup.freeze
87
+ rescue TypeError
88
+ value
89
+ end
90
+ private_class_method :frozen_dup
91
+
28
92
  # Borrow from Rails, when not running Rails
29
93
  def self.camelize(term)
30
94
  string = term.to_s
@@ -34,35 +98,18 @@ module SemanticLogger
34
98
  string
35
99
  end
36
100
 
37
- # Returns the visibility for an instance method
38
- def self.method_visibility(mod, method_name)
39
- method_name = method_name.to_sym
40
- if mod.instance_methods.include?(method_name)
41
- :public
42
- elsif mod.private_instance_methods.include?(method_name)
43
- :private
44
- elsif mod.protected_instance_methods.include?(method_name)
45
- :protected
46
- end
47
- end
48
-
49
101
  # Extract the backtrace stripping off the leading semantic logger entries.
50
102
  # Leaves all other system and gem path entries in place.
51
- def self.extract_backtrace(stack = caller)
52
- while (first = stack.first) && extract_path?(first)
53
- stack.shift
54
- end
55
- stack
56
- end
103
+ # Returns a new Array, leaving the supplied stack unchanged since it can belong to the caller.
104
+ def self.extract_backtrace(stack = caller) = stack.drop_while { |path| extract_path?(path) }
57
105
 
58
- def self.extract_paths
59
- @extract_paths ||= %w[lib/semantic_logger lib/rails_semantic_logger]
60
- end
106
+ # Paths whose entries are stripped from the top of a captured backtrace.
107
+ EXTRACT_PATHS = make_shareable(%w[lib/semantic_logger lib/rails_semantic_logger].freeze)
108
+
109
+ def self.extract_paths = EXTRACT_PATHS
61
110
 
62
111
  # Whether this path should be excluded from any cleansed backtrace
63
- def self.extract_path?(path)
64
- extract_paths.any? { |exclude| path.include?(exclude) }
65
- end
112
+ def self.extract_path?(path) = extract_paths.any? { |exclude| path.include?(exclude) }
66
113
 
67
114
  # Try to strip everything off of the supplied backtrace, until the first application stack entry is at the top.
68
115
  # For example all leading gem paths and built-in ruby code paths are removed from the top.
@@ -77,83 +124,451 @@ module SemanticLogger
77
124
  # Paths to exclude in the stripped backtrace
78
125
  # Includes Gems and built-in Ruby code paths
79
126
  def self.strip_paths
80
- @strip_paths ||=
81
- begin
82
- paths = Gem.path | [Gem.default_dir]
83
- paths << RbConfig::CONFIG["rubylibdir"]
84
- paths
85
- end
127
+ # A copy, since the paths are RubyGems' and RbConfig's own Strings.
128
+ @strip_paths ||= make_shareable(Gem.path | [Gem.default_dir, RbConfig::CONFIG["rubylibdir"]], copy: true)
86
129
  end
87
130
 
88
131
  # Whether this path should be excluded from any cleansed backtrace
89
- def self.strip_path?(path)
90
- strip_paths.any? { |exclude| path.start_with?(exclude) }
132
+ def self.strip_path?(path) = strip_paths.any? { |exclude| path.start_with?(exclude) }
133
+
134
+ # Returns [String] the name of the exception's class as Ruby names it, as in Exception#inspect and
135
+ # #full_message: the constant it was assigned to, such as "Net::ReadTimeout", or, for an
136
+ # anonymous class, which has none, the class as Ruby writes it, such as `#<Class:0x000...>`. It is
137
+ # in UTF-8, whatever the constant's encoding, such as ISO-8859-1, so that it joins with UTF-8 text.
138
+ # Every place that writes an exception's class asks this, so that they all name it alike.
139
+ #
140
+ # Never runs the class's own code, which can override self.name, self.to_s, or self.inspect with
141
+ # code that raises, or that names the class otherwise. Module's own #to_s, bound to the class,
142
+ # returns what Module#name returns when the class has a name, and the class written out when not.
143
+ def self.exception_name(exception) = encode_utf8_string(Module.instance_method(:to_s).bind_call(exception.class))
144
+
145
+ # Returns [String] the exception's message, without raising the error that its #message raises.
146
+ #
147
+ # An exception class can override #message or #to_s with code that raises, such as code that
148
+ # reads a record that is nil, or an abstract #message that raises NotImplementedError. Logging the
149
+ # exception must not replace it with that error, such as the one that a measure_* block re-raises.
150
+ # When #message raises a StandardError or a ScriptError, or does not return a String or an object
151
+ # that converts to one, the message the exception was raised with is returned instead (see
152
+ # .raised_message). Other errors, such as Interrupt, still propagate.
153
+ def self.exception_message(exception)
154
+ String(exception.message)
155
+ rescue StandardError, ScriptError
156
+ raised_message(exception)
157
+ end
158
+
159
+ # Returns [String] the message the exception was raised with, without what its class's own
160
+ # #message or #to_s adds: its class name when it was raised without one. Its class name too when
161
+ # that message cannot be converted to a String, since converting it raised a StandardError or a
162
+ # ScriptError (see .exception_message).
163
+ def self.raised_message(exception)
164
+ Exception.instance_method(:to_s).bind_call(exception)
165
+ rescue StandardError, ScriptError
166
+ exception_name(exception)
167
+ end
168
+
169
+ # Serializes the value to JSON, repairing the data only when necessary.
170
+ #
171
+ # Data that JSON cannot represent appears in well under 1% of log events, so it
172
+ # is wasteful to walk and reallocate the entire structure (see .json_safe) on
173
+ # every call. Instead this attempts `.to_json` directly and only falls back to a
174
+ # repaired copy when serialization fails because of the data:
175
+ # * Invalid UTF-8. Depending on the json gem version this raises
176
+ # Encoding::UndefinedConversionError (an EncodingError) or JSON::GeneratorError.
177
+ # From json 3.1 so does a binary String that holds bytes outside ASCII, even valid UTF-8,
178
+ # which earlier versions write as UTF-8, with a warning that is dropped for log data (see
179
+ # CoreExt::Warning).
180
+ # * Infinity and NaN, which raise JSON::GeneratorError.
181
+ # * Structures nested deeper than the json gem allows, which raise
182
+ # JSON::NestingError (a JSON::ParserError, not a GeneratorError).
183
+ # * A Struct, Data, Set, or OpenStruct instance. The json gem writes one as the String
184
+ # returned by its #to_s, which for each is #inspect: every member is written with
185
+ # #inspect, exposing the instance variables of any object it holds, and without a
186
+ # depth limit, so a deep enough structure raises SystemStackError. The output is
187
+ # checked for that rendering (a JSON String starting with "#<", or "Set[" for a Set on
188
+ # Ruby 4.0), and SystemStackError is rescued, so .json_safe can write the members as a JSON object
189
+ # or array instead. The json gem offers no hook for these short of strict mode,
190
+ # which also rejects common values such as Time, and finding one up front would mean
191
+ # walking every payload on the hot path. ActiveSupport already writes them through
192
+ # #as_json, and escapes "<", so its output never matches the check.
193
+ #
194
+ # Log data can come from untrusted input, for example a float parsed from a request
195
+ # parameter or a deeply nested request body. Without the repair, such a value would
196
+ # make the whole log event impossible to serialize, and so silently dropped.
197
+ #
198
+ # The retry is attempted only once: if it still fails (for example an object whose
199
+ # own #to_json raises), the error propagates unchanged rather than being swallowed.
200
+ def self.to_json(value) = clean_json(value) || json_safe(value).to_json
201
+
202
+ # Returns the value when JSON writes it as it is, otherwise a .json_safe copy, for a writer
203
+ # that serializes the value itself, such as GELF. The check costs one #to_json; only the
204
+ # rare value that needs repairing is copied.
205
+ #
206
+ # That includes a value holding a binary String that json 2.8 through 3.0.x warn about, since
207
+ # the writer's own serializing is not Semantic Logger's, so it would print the warning.
208
+ def self.json_ready(value)
209
+ CoreExt::Warning.unless_binary_string_warned { clean_json(value) } ? value : json_safe(value)
210
+ end
211
+
212
+ # The methods of this file that serialize log data to JSON (see .serializing_log_data?), as
213
+ # their frames are named in a backtrace. A call one of them makes to a method written in C,
214
+ # such as Hash#to_json, is named after that method but located in this file: "to_json".
215
+ SERIALIZERS = make_shareable(%w[to_json clean_json json_safe_object json_safe_members].freeze)
216
+
217
+ # Returns [true|false] whether the code running now was called by this file to serialize log
218
+ # data, such as the json gem raising a warning (see CoreExt::Warning), or an object's own
219
+ # #to_json in a payload: whether the innermost of this file's frames on the stack is one of
220
+ # SERIALIZERS. When it is another of its methods, such as .exception_message calling
221
+ # an exception's #message, the code is not serializing log data, even if log data is being
222
+ # serialized further out.
223
+ #
224
+ # The stack is walked only as far as that frame, however deep it is, such as below nested
225
+ # objects whose #to_json serializes a Hash, so that the answer does not depend on the depth.
226
+ def self.serializing_log_data?
227
+ Thread.each_caller_location { |frame| return SERIALIZERS.include?(frame.base_label) if frame.path == __FILE__ }
228
+ false
91
229
  end
92
230
 
93
- # Serializes the value to JSON, repairing invalid UTF-8 only when necessary.
231
+ # Returns [String] the value's JSON, or nil when .to_json has to repair the data.
232
+ def self.clean_json(value)
233
+ json = value.to_json
234
+ # Almost no JSON holds a "<", and Ruby finds one byte several times faster than a longer
235
+ # substring, so it is looked for first. A String that merely starts with the same text is
236
+ # also repaired; that only costs time, since .json_safe leaves such a String as it is.
237
+ return if json.include?("<") && json.include?(INSPECTED_OBJECT)
238
+ return if INSPECTED_SET && json.include?(INSPECTED_SET)
239
+
240
+ json
241
+ rescue JSON::GeneratorError, JSON::NestingError, EncodingError, SystemStackError
242
+ nil
243
+ end
244
+ private_class_method :clean_json
245
+
246
+ # How the json gem writes an object through its #to_s: a JSON String starting with "#<", as
247
+ # for a Struct, Data, Set, or OpenStruct, whose #to_s is its #inspect.
248
+ INSPECTED_OBJECT = "\"#<".freeze
249
+
250
+ # How the json gem writes a Set where Set#inspect is "Set[...]" (Ruby 4.0), which holds no
251
+ # "#<" unless the Set holds an object. Nil where Set#inspect starts with "#<" too.
252
+ INSPECTED_SET = (::Set.new.inspect.start_with?("#<") ? nil : "\"Set[").freeze
253
+
254
+ # Nesting depth after which .json_safe, and any other copy made by .bounded_structure,
255
+ # replaces a Hash, Array, Struct, or Data with a placeholder. Well below the json gem's
256
+ # default max_nesting of 100, leaving room for the levels that a formatter wraps the payload
257
+ # in.
258
+ MAX_JSON_SAFE_DEPTH = 32
259
+
260
+ # Returns [String] value#inspect, or what the block renders the value as (for example with
261
+ # Amazing Print), without overflowing the stack for a value nested too deeply.
94
262
  #
95
- # Non UTF-8 data appears in well under 1% of log events, so it is wasteful to
96
- # walk and reallocate the entire structure (see .encode_utf8) on every call.
97
- # Instead this attempts `.to_json` directly and only falls back to cleansing
98
- # when serialization fails because of an encoding problem.
263
+ # #inspect has no depth limit: a Hash a few hundred levels deep overflows the stack of a
264
+ # thread. Rescuing the SystemStackError is not enough, since on macOS a second such overflow
265
+ # on the same thread crashes Ruby instead. A value that holds a structure nested deeper than
266
+ # MAX_JSON_SAFE_DEPTH is therefore rendered from a .json_safe copy, as the JSON formatters
267
+ # write it, cut off at that depth with their placeholder. Only that case pays for the copy.
268
+ def self.safe_inspect(value)
269
+ value = json_safe(value) if nested_too_deeply?(value)
270
+ block_given? ? yield(value) : value.inspect
271
+ end
272
+
273
+ # Returns [true|false] whether the value holds a Hash, Array, Struct, or Data nested deeper
274
+ # than MAX_JSON_SAFE_DEPTH, which .json_safe would replace with a placeholder. Never recurses
275
+ # deeper than that itself, and follows the same rules as .json_safe.
276
+ def self.nested_too_deeply?(value, depth = 0)
277
+ case value
278
+ when String, Symbol, Integer, NilClass
279
+ # The most common values, ruled out before the slower checks below.
280
+ false
281
+ when Hash
282
+ depth >= MAX_JSON_SAFE_DEPTH ||
283
+ value.any? { |key, val| nested_too_deeply?(key, depth + 1) || nested_too_deeply?(val, depth + 1) }
284
+ when Array, ::Set
285
+ depth >= MAX_JSON_SAFE_DEPTH || value.any? { |element| nested_too_deeply?(element, depth + 1) }
286
+ when Struct, ::Data
287
+ members_nested_too_deeply?(value, depth)
288
+ else
289
+ open_struct?(value) && members_nested_too_deeply?(value, depth)
290
+ end
291
+ end
292
+
293
+ # Whether the members of a Struct, Data, or OpenStruct are nested too deeply. As in
294
+ # .json_safe_members, a #to_h that does not return a Hash is one level deeper.
295
+ def self.members_nested_too_deeply?(value, depth)
296
+ return true if depth >= MAX_JSON_SAFE_DEPTH
297
+
298
+ members = value.to_h
299
+ members.is_a?(Hash) ? nested_too_deeply?(members, depth) : nested_too_deeply?(members, depth + 1)
300
+ end
301
+ private_class_method :members_nested_too_deeply?
302
+
303
+ # Returns [true|false] whether .json_safe writes the value as a JSON object or array: a Hash,
304
+ # Array, Set, Struct, Data, or OpenStruct. Every one of them would otherwise be written by its
305
+ # #to_s, which is its #inspect.
306
+ def self.structure?(value)
307
+ case value
308
+ when Hash, Array, ::Set, Struct, ::Data
309
+ true
310
+ else
311
+ open_struct?(value)
312
+ end
313
+ end
314
+
315
+ # Whether the value is an OpenStruct. The ostruct gem is only loaded by the application, and
316
+ # is a bundled gem since Ruby 4.0, so Semantic Logger never requires it.
317
+ def self.open_struct?(value)
318
+ # Only recognizes an OpenStruct, so that it is not written through its #inspect.
319
+ defined?(::OpenStruct) && value.is_a?(::OpenStruct) # rubocop:disable Style/OpenStructUse
320
+ end
321
+ private_class_method :open_struct?
322
+
323
+ # Returns a copy of the supplied value that JSON can represent:
324
+ # * Every String is converted to valid UTF-8, as by .encode_utf8, and so is the name of every
325
+ # Symbol, such as a Hash key, that is not UTF-8 or ASCII (see .encode_utf8_symbol).
326
+ # * Infinity and NaN floats become the Strings "Infinity", "-Infinity", and "NaN".
327
+ # * A Struct, Data, or OpenStruct instance becomes a Hash of its members (from #to_h),
328
+ # and a Set an Array, as ActiveSupport's #as_json does, so that its members follow
329
+ # these same rules.
330
+ # * A Hash key that is itself a structure becomes the JSON of its copy, since JSON writes a
331
+ # key with #to_s, which for a structure is its #inspect.
332
+ # * Any other object whose JSON raises because of invalid UTF-8, such as an exception
333
+ # message or a Pathname built from an uploaded file name, becomes its #to_s converted to
334
+ # valid UTF-8.
335
+ # * A Hash, Array, Set, Struct, or Data nested deeper than MAX_JSON_SAFE_DEPTH is replaced
336
+ # with a placeholder String naming its class, such as "#<Hash nested too deeply>".
337
+ # So is one that holds itself, at the point where it would repeat.
338
+ # Any other value is returned as-is.
99
339
  #
100
- # The exception raised for non UTF-8 data depends on the json gem version:
101
- # older versions raise Encoding::UndefinedConversionError (an EncodingError),
102
- # newer versions wrap it as JSON::GeneratorError, so both are rescued. The
103
- # retry is attempted only once: if it still fails (for example a
104
- # JSON::GeneratorError caused by something other than encoding, such as NaN),
105
- # the error propagates unchanged rather than being swallowed.
106
- def self.to_json(value)
340
+ # The recursion never goes deeper than MAX_JSON_SAFE_DEPTH, and the placeholder does
341
+ # not look inside the structure it replaces. Rendering it instead (for example with
342
+ # #inspect) would recurse without limit through an arbitrarily deep structure,
343
+ # raising SystemStackError (or crashing Ruby) on the appender's thread, and would
344
+ # expose the instance variables of any object inside it. Ending a self-referencing
345
+ # structure where it repeats, rather than at that depth, keeps one that holds itself
346
+ # more than once from being copied an exponential number of times.
347
+ def self.json_safe(value, depth = 0, ancestors = nil)
348
+ case value
349
+ when String
350
+ encode_utf8_string(value)
351
+ when Symbol then encode_utf8_symbol(value)
352
+ when Float
353
+ value.finite? ? value : value.to_s
354
+ when Integer, NilClass, TrueClass, FalseClass
355
+ value
356
+ else
357
+ return json_safe_object(value) unless structure?(value)
358
+
359
+ bounded_structure(value, depth, ancestors) { |level, seen| json_safe_members(value, level, seen) }
360
+ end
361
+ end
362
+
363
+ # Returns a bounded copy of a structure, such as a Hash or Array, for .json_safe, .encode_utf8,
364
+ # or an appender that copies log data for a gem that writes it itself: what the block returns for its
365
+ # members, given the next depth and the structures it is inside of, or, for one nested deeper
366
+ # than MAX_JSON_SAFE_DEPTH or that holds itself, a placeholder String naming its class, such
367
+ # as "#<Hash nested too deeply>", in place of the structure.
368
+ def self.bounded_structure(value, depth, ancestors)
369
+ ancestors ||= []
370
+ if depth >= MAX_JSON_SAFE_DEPTH || ancestors.any? { |ancestor| ancestor.equal?(value) }
371
+ return "#<#{value.class} nested too deeply>"
372
+ end
373
+
374
+ ancestors.push(value)
375
+ begin
376
+ yield depth + 1, ancestors
377
+ ensure
378
+ ancestors.pop
379
+ end
380
+ end
381
+
382
+ # Returns any other object as it is, when JSON can write it, otherwise its #to_s converted
383
+ # to valid UTF-8.
384
+ def self.json_safe_object(value)
107
385
  value.to_json
386
+ value
108
387
  rescue JSON::GeneratorError, EncodingError
109
- encode_utf8(value).to_json
388
+ encode_utf8_string(value.to_s)
110
389
  end
390
+ private_class_method :json_safe_object
111
391
 
112
- # Returns a copy of the supplied value with every String converted to valid UTF-8.
392
+ # Returns a copy of the members of a Hash, Array, Set, Struct, Data, or OpenStruct (see
393
+ # .structure_members), each made safe by .json_safe at the supplied depth.
394
+ def self.json_safe_members(value, depth, ancestors)
395
+ members = structure_members(value)
396
+ if members.is_a?(Hash)
397
+ members.each_with_object({}) do |(key, val), hash|
398
+ key = json_safe(key, depth, ancestors)
399
+ key = key.to_json if key.is_a?(Hash) || key.is_a?(Array)
400
+ hash[key] = json_safe(val, depth, ancestors)
401
+ end
402
+ elsif json_array?(value)
403
+ members.map { |element| json_safe(element, depth, ancestors) }
404
+ else
405
+ # A #to_h that does not return a Hash is made safe one level deeper, so that the
406
+ # recursion still ends.
407
+ json_safe(members, depth, ancestors)
408
+ end
409
+ end
410
+ private_class_method :json_safe_members
411
+
412
+ # Returns [true|false] whether the value is a structure that the JSON formatters write as an array
413
+ # of its own elements (see .structure_members): an Array or a Set.
414
+ def self.json_array?(value) = value.is_a?(Array) || value.is_a?(::Set)
415
+
416
+ # Returns the members of a structure (see .structure?), as the JSON formatters write them: a
417
+ # Hash or an Array as it is, the elements of a Set as an Array, and the #to_h of a Struct, Data,
418
+ # or OpenStruct, which is a Hash unless that method returns something else.
419
+ def self.structure_members(value)
420
+ case value
421
+ when Hash, Array
422
+ value
423
+ when ::Set
424
+ value.to_a
425
+ else
426
+ value.to_h
427
+ end
428
+ end
429
+
430
+ # Returns a copy of the supplied value with every String converted to valid UTF-8, and every
431
+ # Symbol whose name is not UTF-8 or ASCII converted the same way (see .encode_utf8_symbol).
113
432
  #
114
433
  # Recurses through Hash and Array structures, cleansing both keys and values.
115
434
  # Strings that are already valid UTF-8 are returned unchanged (the common case),
116
- # so the fast path allocates nothing. Any other value (Symbol, Numeric, Time, nil,
117
- # ...) is returned as-is.
435
+ # and so are Symbols that are UTF-8 or ASCII, so the fast path allocates nothing. Any
436
+ # other value (Numeric, Time, nil, a Struct, ...) is returned as-is, without looking
437
+ # inside it.
118
438
  #
119
- # Used by .to_json on the rare failing path, and directly by formatters that
120
- # serialize per value or emit to a non-JSON sink (where a single `.to_json`
121
- # rescue boundary cannot catch an intermediate failure).
122
- def self.encode_utf8(value)
439
+ # A Hash or Array nested deeper than MAX_JSON_SAFE_DEPTH, or that holds itself, is
440
+ # replaced where it is too deep or repeats with the placeholder that .json_safe writes,
441
+ # such as "#<Hash nested too deeply>", so that the copy is bounded, as .json_safe is.
442
+ #
443
+ # Used by formatters that serialize per value or emit to a non-JSON sink (where a
444
+ # single `.to_json` rescue boundary cannot catch an intermediate failure), and by
445
+ # appenders that hand log data to a gem that writes it itself.
446
+ def self.encode_utf8(value, depth = 0, ancestors = nil)
123
447
  case value
124
448
  when String
125
449
  encode_utf8_string(value)
126
- when Hash
127
- value.each_with_object({}) do |(key, val), hash|
128
- hash[encode_utf8(key)] = encode_utf8(val)
129
- end
130
- when Array
131
- value.map { |element| encode_utf8(element) }
450
+ when Symbol then encode_utf8_symbol(value)
451
+ when Hash, Array
452
+ bounded_structure(value, depth, ancestors) { |level, seen| encode_utf8_members(value, level, seen) }
132
453
  else
133
454
  value
134
455
  end
135
456
  end
136
457
 
458
+ # Returns a copy of the members of a Hash or Array, each converted by .encode_utf8.
459
+ def self.encode_utf8_members(value, depth, ancestors)
460
+ return value.map { |element| encode_utf8(element, depth, ancestors) } if value.is_a?(Array)
461
+
462
+ value.each_with_object({}) do |(key, val), hash|
463
+ hash[encode_utf8(key, depth, ancestors)] = encode_utf8(val, depth, ancestors)
464
+ end
465
+ end
466
+ private_class_method :encode_utf8_members
467
+
137
468
  # Options used when transcoding a string to UTF-8.
138
469
  # Invalid byte sequences and characters that cannot be represented in UTF-8 are
139
470
  # dropped rather than substituted, matching the preference in issue #180.
140
471
  ENCODE_UTF8_OPTIONS = {invalid: :replace, undef: :replace, replace: "".freeze}.freeze
141
472
 
142
473
  # Returns the string converted to valid UTF-8, dropping any invalid bytes.
474
+ #
475
+ # Binary text, such as a response body, Base64-decoded text, or a C extension's error message,
476
+ # and US-ASCII text that holds bytes outside ASCII, such as a file read where no locale is set,
477
+ # do not say which characters those bytes are. They are read as the UTF-8 they usually hold,
478
+ # keeping its characters, as the json gem did before 3.1. Converting them would drop every byte
479
+ # outside ASCII, valid UTF-8 or not, since neither encoding defines one. Text in any other
480
+ # encoding, such as ISO-8859-1, is converted, and text tagged UTF-16 or UTF-32 (not UTF-16LE
481
+ # and the like) without a byte order mark is read as big-endian (see .encode_byte_ordered).
143
482
  def self.encode_utf8_string(string)
144
- return string if string.encoding == Encoding::UTF_8 && string.valid_encoding?
145
-
146
- if string.encoding == Encoding::UTF_8
147
- # Correctly tagged as UTF-8 but contains invalid byte sequences.
148
- string.scrub("")
483
+ case string.encoding
484
+ when Encoding::UTF_8
485
+ string.valid_encoding? ? string : string.scrub("")
486
+ when Encoding::BINARY, Encoding::US_ASCII
487
+ read_as_utf8(string)
488
+ when Encoding::UTF_16, Encoding::UTF_32 then encode_byte_ordered(string)
149
489
  else
150
- # Different encoding (e.g. ASCII-8BIT / Latin-1): transcode into UTF-8.
151
490
  string.encode(Encoding::UTF_8, **ENCODE_UTF8_OPTIONS)
152
491
  end
153
492
  rescue EncodingError
154
- # Last resort for encodings without a converter to UTF-8: reinterpret the
155
- # raw bytes as UTF-8 and drop anything invalid. Logging must never raise.
156
- string.dup.force_encoding(Encoding::UTF_8).scrub("")
493
+ # Last resort for encodings without a converter to UTF-8. Logging must never raise.
494
+ read_as_utf8(string)
495
+ end
496
+
497
+ # Returns [Symbol] the Symbol, or, when its name is neither UTF-8 nor ASCII, a Symbol named with
498
+ # that name converted to valid UTF-8 (see .encode_utf8_string).
499
+ #
500
+ # A Symbol is named in the encoding of the text it was made from, such as a binary key from a
501
+ # request turned into a Symbol, which JSON cannot always write once it holds bytes outside
502
+ # ASCII: from json 3.1 not even valid UTF-8, and on CRuby with earlier versions not invalid
503
+ # bytes, nor, from json 2.9, UTF-8 bytes tagged US-ASCII. A UTF-8 Symbol is always valid.
504
+ def self.encode_utf8_symbol(symbol)
505
+ symbol.name.ascii_only? || symbol.encoding == Encoding::UTF_8 ? symbol : encode_utf8_string(symbol.name).to_sym
506
+ end
507
+
508
+ # Returns [String] a copy of the string's bytes read as UTF-8, without its invalid bytes.
509
+ private_class_method def self.read_as_utf8(string) = String.new(string, encoding: Encoding::UTF_8).scrub!("")
510
+
511
+ # Returns [String] UTF-16 or UTF-32 text converted to valid UTF-8. These encodings say their
512
+ # byte order with a byte order mark at the start, and Ruby's converter drops all the text that
513
+ # does not have one. Unicode reads such text as big-endian, and so does this.
514
+ private_class_method def self.encode_byte_ordered(string)
515
+ big_endian = string.encoding == Encoding::UTF_16 ? Encoding::UTF_16BE : Encoding::UTF_32BE
516
+ mark = "\uFEFF".encode(big_endian).b
517
+ string = String.new(string, encoding: big_endian) unless string.b.start_with?(mark, mark.reverse)
518
+ string.encode(Encoding::UTF_8, **ENCODE_UTF8_OPTIONS)
519
+ end
520
+
521
+ # Returns [String] the texts joined into a new String, such as a log message and an exception's
522
+ # message, whatever their encodings.
523
+ #
524
+ # Texts are joined as they are, so that text in an encoding such as ISO-8859-1 can still be
525
+ # joined with the application's other text in that encoding. Two texts are converted to valid
526
+ # UTF-8 first (see .encode_utf8_string) only when joining them would raise, such as for UTF-8
527
+ # and binary texts that both hold bytes outside ASCII, or would make text that is not binary
528
+ # binary, such as an ASCII message joined with a binary exception message.
529
+ #
530
+ # Each text is formatted as interpolation would, rather than added or converted with #to_s, so
531
+ # that a String subclass whose #+ escapes the text added to it, such as
532
+ # ActiveSupport::SafeBuffer, is joined as plain text, and an object whose #to_s does not return a
533
+ # String is still joined.
534
+ #
535
+ # Plain Strings that are all UTF-8, the usual texts, always join as they are, so they are joined
536
+ # without those checks, which take several times as long. With an explicit separator, a new
537
+ # empty String, so that a global `$,` set by another library is not added between them.
538
+ def self.join_texts(*texts)
539
+ return texts.join(+"") if texts.all? { |text| text.instance_of?(String) && text.encoding == Encoding::UTF_8 }
540
+
541
+ texts.map { |text| format("%s", text) }.reduce do |joined, text|
542
+ encoding = Encoding.compatible?(joined, text)
543
+ joinable = encoding && (encoding != Encoding::BINARY || joined.encoding == Encoding::BINARY)
544
+ joinable ? "#{joined}#{text}" : "#{encode_utf8_string(joined)}#{encode_utf8_string(text)}"
545
+ end
546
+ end
547
+
548
+ # Returns [String] the lines, such as those of a backtrace, joined into a new String with a line
549
+ # break between each, whatever their encodings: as they are, as Array#join joins them, or, when
550
+ # that would raise, such as for a UTF-8 line and an ISO-8859-1 one that both hold bytes outside
551
+ # ASCII, with each line formatted as .join_texts formats a text and converted to valid UTF-8
552
+ # (see .encode_utf8_string), which leaves a valid UTF-8 line as it is.
553
+ #
554
+ # Joined text that is binary or US-ASCII and holds bytes outside ASCII is converted to valid UTF-8
555
+ # too, such as for an ASCII line and a binary one, or for Ruby's own backtrace lines, which are
556
+ # US-ASCII where no locale is set, in a directory such as café. Unlike .join_texts, which keeps
557
+ # text binary when it starts with binary text, such as when every text is binary, this converts
558
+ # such text even when every line is binary. Each line of such text is in that encoding or
559
+ # ASCII-only, so it is converted whole, as each line would be. Its encoding is checked first,
560
+ # since checking that it is ASCII-only reads the whole text.
561
+ #
562
+ # Lines are converted only when they cannot be joined as they are, which is rare, since checking
563
+ # each of what can be dozens of lines would double the time it takes to format an exception.
564
+ # Each is then converted once and the lines joined once, rather than pair by pair as .join_texts
565
+ # joins texts, which for a backtrace of thousands of lines takes a time that grows with the
566
+ # square of their number.
567
+ def self.join_lines(lines)
568
+ text = lines.join("\n")
569
+ (text.encoding in Encoding::BINARY | Encoding::US_ASCII) && !text.ascii_only? ? encode_utf8_string(text) : text
570
+ rescue Encoding::CompatibilityError
571
+ lines.map { |line| encode_utf8_string(format("%s", line)) }.join("\n")
157
572
  end
158
573
  end
159
574
  end
@@ -1,3 +1,3 @@
1
1
  module SemanticLogger
2
- VERSION = "5.1.0".freeze
2
+ VERSION = "5.3.0".freeze
3
3
  end