lumberjack 1.4.2 → 2.0.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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/ARCHITECTURE.md +524 -176
  3. data/CHANGELOG.md +89 -0
  4. data/README.md +604 -211
  5. data/UPGRADE_GUIDE.md +80 -0
  6. data/VERSION +1 -1
  7. data/lib/lumberjack/attribute_formatter.rb +451 -0
  8. data/lib/lumberjack/attributes_helper.rb +100 -0
  9. data/lib/lumberjack/context.rb +120 -23
  10. data/lib/lumberjack/context_logger.rb +620 -0
  11. data/lib/lumberjack/device/buffer.rb +209 -0
  12. data/lib/lumberjack/device/date_rolling_log_file.rb +10 -62
  13. data/lib/lumberjack/device/log_file.rb +76 -29
  14. data/lib/lumberjack/device/logger_wrapper.rb +137 -0
  15. data/lib/lumberjack/device/multi.rb +92 -30
  16. data/lib/lumberjack/device/null.rb +26 -8
  17. data/lib/lumberjack/device/size_rolling_log_file.rb +13 -54
  18. data/lib/lumberjack/device/test.rb +337 -0
  19. data/lib/lumberjack/device/writer.rb +184 -176
  20. data/lib/lumberjack/device.rb +134 -15
  21. data/lib/lumberjack/device_registry.rb +90 -0
  22. data/lib/lumberjack/entry_formatter.rb +357 -0
  23. data/lib/lumberjack/fiber_locals.rb +55 -0
  24. data/lib/lumberjack/forked_logger.rb +143 -0
  25. data/lib/lumberjack/formatter/date_time_formatter.rb +14 -3
  26. data/lib/lumberjack/formatter/exception_formatter.rb +12 -2
  27. data/lib/lumberjack/formatter/id_formatter.rb +13 -1
  28. data/lib/lumberjack/formatter/inspect_formatter.rb +14 -1
  29. data/lib/lumberjack/formatter/multiply_formatter.rb +10 -0
  30. data/lib/lumberjack/formatter/object_formatter.rb +13 -1
  31. data/lib/lumberjack/formatter/pretty_print_formatter.rb +15 -2
  32. data/lib/lumberjack/formatter/redact_formatter.rb +18 -3
  33. data/lib/lumberjack/formatter/round_formatter.rb +12 -0
  34. data/lib/lumberjack/formatter/string_formatter.rb +9 -1
  35. data/lib/lumberjack/formatter/strip_formatter.rb +13 -1
  36. data/lib/lumberjack/formatter/structured_formatter.rb +18 -2
  37. data/lib/lumberjack/formatter/tagged_message.rb +10 -32
  38. data/lib/lumberjack/formatter/tags_formatter.rb +32 -0
  39. data/lib/lumberjack/formatter/truncate_formatter.rb +8 -1
  40. data/lib/lumberjack/formatter.rb +271 -141
  41. data/lib/lumberjack/formatter_registry.rb +84 -0
  42. data/lib/lumberjack/io_compatibility.rb +133 -0
  43. data/lib/lumberjack/local_log_template.rb +209 -0
  44. data/lib/lumberjack/log_entry.rb +154 -79
  45. data/lib/lumberjack/log_entry_matcher/score.rb +276 -0
  46. data/lib/lumberjack/log_entry_matcher.rb +126 -0
  47. data/lib/lumberjack/logger.rb +328 -556
  48. data/lib/lumberjack/message_attributes.rb +38 -0
  49. data/lib/lumberjack/rack/context.rb +66 -15
  50. data/lib/lumberjack/rack.rb +0 -2
  51. data/lib/lumberjack/remap_attribute.rb +24 -0
  52. data/lib/lumberjack/severity.rb +52 -15
  53. data/lib/lumberjack/tag_context.rb +8 -71
  54. data/lib/lumberjack/tag_formatter.rb +22 -188
  55. data/lib/lumberjack/tags.rb +15 -21
  56. data/lib/lumberjack/template.rb +252 -62
  57. data/lib/lumberjack/template_registry.rb +60 -0
  58. data/lib/lumberjack/utils.rb +198 -48
  59. data/lib/lumberjack.rb +167 -59
  60. data/lumberjack.gemspec +4 -2
  61. metadata +41 -15
  62. data/lib/lumberjack/device/rolling_log_file.rb +0 -145
  63. data/lib/lumberjack/rack/request_id.rb +0 -31
  64. data/lib/lumberjack/rack/unit_of_work.rb +0 -21
  65. data/lib/lumberjack/tagged_logger_support.rb +0 -81
  66. data/lib/lumberjack/tagged_logging.rb +0 -29
@@ -1,16 +1,36 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "formatter_registry"
4
+
3
5
  module Lumberjack
4
- # This class controls the conversion of log entry messages into a loggable format. This allows you
5
- # to log any object you want and have the logging system deal with converting it into a string.
6
+ # Formatter controls the conversion of log entry messages into a loggable format, allowing you
7
+ # to log any object type and have the logging system handle the string conversion automatically.
8
+ #
9
+ # The formatter system works by associating formatting rules with specific classes using the {#add} method.
10
+ # When an object is logged, the formatter finds the most specific formatter for that object's class
11
+ # hierarchy and applies it to convert the object into a string representation.
12
+ #
13
+ # Formatters can be:
6
14
  #
7
- # Formats are added to a Formatter by associating them with a class using the +add+ method. Formats
8
- # are any object that responds to the +call+ method.
15
+ # - Predefined formatters: Accessed by symbol (e.g., +:pretty_print+, +:truncate+)
16
+ # - Custom objects: Any object responding to +#call(object)+
17
+ # - Blocks: Inline formatting logic
18
+ # - Classes: Instantiated automatically with optional arguments
9
19
  #
10
- # By default, all object will be converted to strings using their inspect method except for Strings
11
- # and Exceptions. Strings are not converted and Exceptions are converted using the ExceptionFormatter.
20
+ # The formatter includes optimizations for common primitive types (String, Integer, Float, Boolean)
21
+ # to avoid unnecessary formatting overhead when custom formatters aren't defined for these types.
12
22
  #
13
- # Enumerable objects (including Hash and Array) will call the formatter recursively for each element.
23
+ # @example Basic formatter usage
24
+ # formatter = Lumberjack::Formatter.new
25
+ # formatter.add(MyClass, :pretty_print)
26
+ # formatter.add(Array) { |vals| vals.join(", ") }
27
+ # result = formatter.format(my_object)
28
+ #
29
+ # @example Building a custom formatter
30
+ # formatter = Lumberjack::Formatter.build do |config|
31
+ # config.add(User, :id) # Only log user IDs
32
+ # config.add(BigDecimal, :round, 2) # Round decimals to 2 places
33
+ # end
14
34
  class Formatter
15
35
  require_relative "formatter/date_time_formatter"
16
36
  require_relative "formatter/exception_formatter"
@@ -24,197 +44,307 @@ module Lumberjack
24
44
  require_relative "formatter/string_formatter"
25
45
  require_relative "formatter/strip_formatter"
26
46
  require_relative "formatter/structured_formatter"
47
+ require_relative "formatter/tags_formatter"
27
48
  require_relative "formatter/truncate_formatter"
28
49
  require_relative "formatter/tagged_message"
29
50
 
30
51
  class << self
31
- # Returns a new empty formatter with no mapping. For historical reasons, a formatter
32
- # is initialized with mappings to help output objects as strings. This will return one
33
- # without the default mappings.
52
+ # Build a new formatter using a configuration block. The block receives the new formatter
53
+ # as a parameter, allowing you to configure it with methods like +add+, +remove+, etc.
54
+ #
55
+ # @yield [formatter] A block that configures the formatter.
56
+ # @return [Lumberjack::Formatter] A new configured formatter.
34
57
  #
35
- # @return [Lumberjack::Formatter] a new empty formatter
58
+ # @example
59
+ # formatter = Lumberjack::Formatter.build do |config|
60
+ # config.add(User, :id) # Only show user IDs
61
+ # config.add(SecretToken) { |token| "[REDACTED]" }
62
+ # config.remove(Exception) # Don't format exceptions specially
63
+ # end
64
+ def build(&block)
65
+ formatter = new
66
+ block&.call(formatter)
67
+ formatter
68
+ end
69
+
70
+ # Create a new empty formatter with no mappings. This is an alias for #new.
71
+ #
72
+ # @return [Lumberjack::Formatter] A new formatter with no default mappings.
73
+ # @deprecated Use #new instead.
36
74
  def empty
37
- new.clear
75
+ Utils.deprecated("Formatter.empty", "Lumberjack::Formatter.empty is deprecated and will be removed in version 2.1; use new instead.") do
76
+ new
77
+ end
78
+ end
79
+
80
+ # Create a new formatter with default mappings.
81
+ #
82
+ # Object: inspect formatter
83
+ # Exception: exception formatter
84
+ # Enumerable: structured formatter
85
+ #
86
+ # @return [Lumberjack::Formatter] A new formatter with default mappings.
87
+ def default
88
+ build do |config|
89
+ config.add(Object, :inspect)
90
+ config.add(Exception, :exception)
91
+ config.add(Enumerable, :structured)
92
+ end
38
93
  end
39
94
  end
40
95
 
96
+ # Create a new formatter with default mappings for common Ruby types.
97
+ # The default configuration provides sensible formatting for most use cases:
98
+ # - Object: Uses inspect for debugging-friendly output
99
+ # - Exception: Formats with stack trace details
100
+ # - Enumerable: Recursively formats collections (Arrays, Hashes, etc.)
101
+ #
102
+ # @return [Lumberjack::Formatter] A new formatter with default mappings.
41
103
  def initialize
42
104
  @class_formatters = {}
43
- @module_formatters = {}
44
- structured_formatter = StructuredFormatter.new(self)
45
- add([String, Numeric, TrueClass, FalseClass], :object)
46
- add(Object, InspectFormatter.new)
47
- add(Exception, :exception)
48
- add(Enumerable, structured_formatter)
105
+ @has_string_formatter = false
106
+ @has_numeric_formatter = false
107
+ @has_boolean_formatter = false
49
108
  end
50
109
 
51
- # Add a formatter for a class. The formatter can be specified as either an object
52
- # that responds to the +call+ method or as a symbol representing one of the predefined
53
- # formatters, or as a block to the method call.
54
- #
55
- # The predefined formatters are:
56
- # - :date_time
57
- # - :exception
58
- # - :id
59
- # - :inspect
60
- # - :object
61
- # - :pretty_print
62
- # - :string
63
- # - :strip
64
- # - :structured
65
- # - :truncate
66
- #
67
- # You can add multiple classes at once by passing an array of classes.
68
- #
69
- # You can also pass class names as strings instead of the classes themselves. This can
70
- # help avoid loading dependency issues. This applies only to classes; modules cannot be
71
- # passed in as strings.
72
- #
73
- # @param klass [Class, Module, String, Array<Class, Module, String>] The class or module to add a formatter for.
74
- # @param formatter [Symbol, Class, String, #call] The formatter to use for the class.
75
- # If a symbol is passed in, it will be used to load one of the predefined formatters.
76
- # If a class is passed in, it will be initialized with the args passed in.
77
- # Otherwise, the object will be used as the formatter and must respond to call method.
78
- # @param args [Array] Arguments to pass to the formatter when it is initialized.
79
- # @yield [obj] A block that will be used as the formatter for the class.
80
- # @yieldparam [Object] obj The object to format.
81
- # @yieldreturn [String] The formatted string.
82
- # @return [self] Returns itself so that add statements can be chained together.
83
- #
84
- # @example
85
- #
86
- # # Use a predefined formatter
87
- # formatter.add(MyClass, :pretty_print)
88
- #
89
- # # Pass in a formatter object
90
- # formatter.add(MyClass, Lumberjack::Formatter::PrettyPrintFormatter.new)
91
- #
92
- # # Use a block
93
- # formatter.add(MyClass){|obj| obj.humanize}
94
- #
95
- # # Add statements can be chained together
96
- # formatter.add(MyClass, :pretty_print).add(YourClass){|obj| obj.humanize}
110
+ # Add a formatter for a specific class or classes. The formatter determines how objects
111
+ # of that class will be converted to strings when logged.
112
+ #
113
+ # The formatter can be specified in several ways:
114
+ # - Symbol: References a predefined formatter (see list below)
115
+ # - Class: Will be instantiated with optional arguments
116
+ # - Object: Must respond to +#call(object)+ method
117
+ # - Block: Inline formatting logic
118
+ #
119
+ # Formatters can be referenced by name from the formatter registry. These formatters
120
+ # are available out of the box. Some of them require an argument to be provided as well.
121
+ #
122
+ # - +:date_time+ - Formats time objects with a customizable format (takes the format string as an argument)
123
+ # - +:exception+ - Formats exceptions with stack trace details
124
+ # - +:id+ - Extracts object ID or specified ID field
125
+ # - +:inspect+ - Uses Ruby's inspect method for debugging output
126
+ # - +:multiply+ - Multiplies numeric values by a factor (requires the factor as an argument)
127
+ # - +:object+ - Generic object formatter with custom methods
128
+ # - +:pretty_print+ - Pretty-prints objects using PP library
129
+ # - +:redact+ - Redacts sensitive information from objects
130
+ # - +:round+ - Rounds numeric values to specified precision (takes the precision as an argument; defaults to 3 decimal places)
131
+ # - +:string+ - Converts objects to strings using to_s
132
+ # - +:strip+ - Strips whitespace from string representations
133
+ # - +:structured+ - Recursively formats structured data (Arrays, Hashes)
134
+ # - +:tags+ - Formats an array or hash of values in the format "[a] [b] [c=d]"
135
+ # - +:truncate+ - Truncates long strings to specified length (takes the length as an argument)
136
+ #
137
+ # Classes can be specified as:
138
+ #
139
+ # - Class objects: Direct class references
140
+ # - Arrays: Multiple classes at once
141
+ # - Strings: Class names to avoid loading dependencies
142
+ #
143
+ # @param klass [Class, Module, String, Array<Class, Module, String>] The class(es) to format.
144
+ # @param formatter [Symbol, Class, #call, nil] The formatter to use.
145
+ # @param args [Array] Arguments passed to formatter constructor (when formatter is a Class).
146
+ # @yield [obj] Block-based formatter that receives the object to format.
147
+ # @yieldparam obj [Object] The object to format.
148
+ # @yieldreturn [String] The formatted string representation.
149
+ # @return [self] Returns self for method chaining.
150
+ #
151
+ # @example Using predefined formatters
152
+ # formatter.add(Float, :round, 2) # Round floats to 2 decimal places
153
+ # formatter.add(Time, :date_time, "%Y-%m-%d") # Custom time format
154
+ # formatter.add([User, Admin], :id) # Show only IDs for user objects
155
+ #
156
+ # @example Using custom formatters
157
+ # formatter.add(MyClass, MyFormatter.new) # Custom formatter object
158
+ # formatter.add("BigDecimal", RoundFormatter, 4) # Class with arguments
159
+ #
160
+ # @example Method chaining
161
+ # formatter.add(User, :id)
162
+ # .add(BigDecimal, :round, 2)
97
163
  def add(klass, formatter = nil, *args, &block)
98
164
  formatter ||= block
99
- if formatter.nil?
100
- remove(klass)
101
- else
102
- formatter_class_name = nil
103
- if formatter.is_a?(Symbol)
104
- formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/) { |m| $~[2].upcase }}Formatter"
105
- elsif formatter.is_a?(String)
106
- formatter_class_name = formatter
107
- end
108
- if formatter_class_name
109
- formatter = Formatter.const_get(formatter_class_name)
110
- end
111
165
 
112
- if formatter.is_a?(Class)
113
- formatter = formatter.new(*args)
114
- end
166
+ return remove(klass) if formatter.nil?
115
167
 
116
- Array(klass).each do |k|
117
- if k.instance_of?(Module)
118
- @module_formatters[k] = formatter
119
- else
120
- k = k.name if k.is_a?(Class)
121
- @class_formatters[k] = formatter
122
- end
123
- end
168
+ if formatter.is_a?(Symbol)
169
+ formatter = FormatterRegistry.formatter(formatter, *args)
170
+ elsif formatter.is_a?(Class)
171
+ formatter = formatter.new(*args)
172
+ end
173
+
174
+ raise ArgumentError.new("formatter must respond to call") unless formatter.respond_to?(:call)
175
+
176
+ Array(klass).each do |k|
177
+ @class_formatters[k.to_s] = formatter
124
178
  end
179
+
180
+ set_optimized_flags!
181
+
125
182
  self
126
183
  end
127
184
 
128
- # Remove the formatter associated with a class. Remove statements can be chained together.
129
- #
130
- # You can remove multiple classes at once by passing an array of classes.
131
- #
132
- # You can also pass class names as strings instead of the classes themselves. This can
133
- # help avoid loading dependency issues. This applies only to classes; modules cannot be
134
- # passed in as strings.
185
+ # Remove formatter associations for one or more classes. This reverts the classes
186
+ # to use the default Object formatter (inspect method) or no formatting if no default exists.
135
187
  #
136
- # @param klass [Class, Module, String, Array<Class, Module, String>] The class or module to remove the formatters for.
137
- # @return [self] Returns itself so that remove statements can be chained together.
188
+ # @param klass [Class, Module, String, Array<Class, Module, String>] The class(es) to remove formatters for.
189
+ # @return [self] Returns self for method chaining.
138
190
  def remove(klass)
139
191
  Array(klass).each do |k|
140
- if k.instance_of?(Module)
141
- @module_formatters.delete(k)
142
- else
143
- k = k.name if k.is_a?(Class)
144
- @class_formatters.delete(k)
145
- end
192
+ @class_formatters.delete(k.to_s)
193
+ end
194
+
195
+ set_optimized_flags!
196
+
197
+ self
198
+ end
199
+
200
+ # Extend this formatter by merging the formats defined in the provided formatter into this one.
201
+ #
202
+ # @param formatter [Lumberjack::Formatter] The formatter to merge.
203
+ # @return [self] Returns self for method chaining.
204
+ def include(formatter)
205
+ unless formatter.is_a?(Lumberjack::Formatter)
206
+ raise ArgumentError.new("formatter must be a Lumberjack::Formatter")
207
+ end
208
+
209
+ formatter.instance_variable_get(:@class_formatters).each do |class_name, fmttr|
210
+ add(class_name, fmttr)
211
+ end
212
+
213
+ self
214
+ end
215
+
216
+ # Extend this formatter by adding the formats defined in the provided formatter into this one.
217
+ # Formats defined in this formatter will take precedence and not be overridden.
218
+ #
219
+ # @param formatter [Lumberjack::Formatter] The formatter to merge.
220
+ # @return [self] Returns self for method chaining.
221
+ def prepend(formatter)
222
+ unless formatter.is_a?(Lumberjack::Formatter)
223
+ raise ArgumentError.new("formatter must be a Lumberjack::Formatter")
224
+ end
225
+
226
+ formatter.instance_variable_get(:@class_formatters).each do |class_name, fmttr|
227
+ add(class_name, fmttr) unless @class_formatters.include?(class_name)
146
228
  end
229
+
147
230
  self
148
231
  end
149
232
 
150
- # Remove all formatters including the default formatter. Can be chained to add method calls.
233
+ # Remove all formatter associations, including defaults. This creates a completely
234
+ # empty formatter where all objects will be passed through unchanged.
151
235
  #
152
- # @return [self] Returns itself so that clear statements can be chained together.
236
+ # @return [self] Returns self for method chaining.
153
237
  def clear
154
238
  @class_formatters.clear
155
- @module_formatters.clear
239
+ set_optimized_flags!
240
+
156
241
  self
157
242
  end
158
243
 
159
- # Return true if their are no registered formatters.
244
+ # Check if the formatter has any registered formatters.
160
245
  #
161
- # @return [Boolean] true if there are no registered formatters, false otherwise.
246
+ # @return [Boolean] true if no formatters are registered, false otherwise.
162
247
  def empty?
163
- @class_formatters.empty? && @module_formatters.empty?
248
+ @class_formatters.empty?
164
249
  end
165
250
 
166
- # Format a message object by applying all formatters attached to it.
251
+ # Format an object by applying the appropriate formatter based on its class hierarchy.
252
+ # The formatter searches up the class hierarchy to find the most specific formatter available.
167
253
  #
168
- # @param message [Object] The message object to format.
169
- # @return [Object] The formatted object.
170
- def format(message)
171
- formatter = formatter_for(message.class)
172
- if formatter&.respond_to?(:call)
173
- begin
174
- formatter.call(message)
175
- rescue SystemStackError, StandardError => e
176
- error_message = e.class.name
177
- error_message = "#{error_message} #{e.message}" if e.message && e.message != ""
178
- warn("<Error formatting #{message.class.name}: #{error_message}>")
179
- "<Error formatting #{message.class.name}: #{error_message}>"
254
+ # @param value [Object] The object to format.
255
+ # @return [Object] The formatted representation (usually a String).
256
+ def format(value)
257
+ # These primitive types are the most common in logs and so are optimized here
258
+ # for the normal case where a custom formatter has not been defined.
259
+ case value
260
+ when String
261
+ return value unless @has_string_formatter
262
+ when Integer, Float
263
+ return value unless @has_numeric_formatter
264
+ when Numeric
265
+ if defined?(BigDecimal) && value.is_a?(BigDecimal)
266
+ return value unless @has_numeric_formatter
180
267
  end
181
- else
182
- message
268
+ when true, false
269
+ return value unless @has_boolean_formatter
270
+ end
271
+
272
+ if value.respond_to?(:to_log_format) && !@class_formatters.include?(value.class.name)
273
+ return value.to_log_format
183
274
  end
275
+
276
+ formatter = formatter_for(value.class)
277
+ value = formatter.call(value) if formatter&.respond_to?(:call)
278
+ value
279
+ rescue SystemStackError, StandardError => e
280
+ error_message = e.class.name
281
+ error_message = "#{error_message} #{e.message}" if e.message && e.message != ""
282
+ warn("<Error formatting #{value.class.name}: #{error_message}>")
283
+ "<Error formatting #{value.class.name}: #{error_message}>"
184
284
  end
185
285
 
186
- # Compatibility with the Logger::Formatter signature. This method will just convert the message
187
- # object to a string and ignores the other parameters.
286
+ # Compatibility method for Ruby's standard Logger::Formatter interface. This allows
287
+ # the Formatter to be used directly as a logger formatter, though it only uses the
288
+ # message parameter and ignores severity, timestamp, and progname.
188
289
  #
189
- # @param severity [Integer, String, Symbol] The severity of the message.
190
- # @param timestamp [Time] The time the message was logged.
191
- # @param progname [String] The name of the program logging the message.
290
+ # @param severity [Integer, String, Symbol] The log severity (ignored).
291
+ # @param timestamp [Time] The log timestamp (ignored).
292
+ # @param progname [String] The program name (ignored).
192
293
  # @param msg [Object] The message object to format.
294
+ # @return [String] The formatted message with line separator.
193
295
  def call(severity, timestamp, progname, msg)
194
296
  formatted_message = format(msg)
195
- formatted_message = formatted_message.message if formatted_message.is_a?(TaggedMessage)
297
+ formatted_message = formatted_message.message if formatted_message.is_a?(MessageAttributes)
196
298
  "#{formatted_message}#{Lumberjack::LINE_SEPARATOR}"
197
299
  end
198
300
 
199
- # Find the formatter for a class by looking it up using the class hierarchy.
301
+ # Find the most appropriate formatter for a class by searching up the class hierarchy.
302
+ # Returns the first formatter found by walking through the class's ancestors.
200
303
  #
304
+ # @param klass [Class] The class to find a formatter for.
305
+ # @return [#call, nil] The formatter object, or nil if no formatter is found.
201
306
  # @api private
202
307
  def formatter_for(klass)
203
- return nil if empty?
204
-
205
- check_modules = true
206
- until klass.nil?
207
- formatter = @class_formatters[klass.name]
208
- return formatter if formatter
308
+ return nil if @class_formatters.empty?
209
309
 
210
- if check_modules
211
- _, formatter = @module_formatters.detect { |mod, f| klass.include?(mod) }
212
- check_modules = false
213
- return formatter if formatter
310
+ unless klass.is_a?(Module)
311
+ begin
312
+ klass = Object.const_get(klass.to_s)
313
+ rescue NameError
314
+ return @class_formatters[klass.to_s]
214
315
  end
316
+ end
215
317
 
216
- klass = klass.superclass
318
+ formatter = nil
319
+ has_to_log_format = klass.public_method_defined?(:to_log_format) if klass.is_a?(Module)
320
+ klass.ancestors.detect do |ancestor|
321
+ break if has_to_log_format && ancestor == Object
322
+
323
+ formatter = @class_formatters[ancestor.name]
324
+ break if formatter
217
325
  end
326
+ formatter
327
+ end
328
+
329
+ # Check if a formatter exists for a specific class or class name.
330
+ #
331
+ # @param class_or_name [Class, Module, String] The class or class name to check.
332
+ # @return [Boolean] true if a formatter exists, false otherwise.
333
+ def include?(class_or_name)
334
+ @class_formatters.include?(class_or_name.to_s)
335
+ end
336
+
337
+ private
338
+
339
+ # Update internal optimization flags based on currently registered formatters.
340
+ # This enables fast-path optimization for common primitive types.
341
+ #
342
+ # @return [void]
343
+ # @api private
344
+ def set_optimized_flags!
345
+ @has_string_formatter = @class_formatters.include?("String")
346
+ @has_numeric_formatter = @class_formatters.slice("Integer", "Float", "BigDecimal", "Numeric").any?
347
+ @has_boolean_formatter = @class_formatters.include?("TrueClass") || @class_formatters.include?("FalseClass")
218
348
  end
219
349
  end
220
350
  end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lumberjack
4
+ # The formatter registry is used for setting up names to represent Formatter classes. It is used
5
+ # in the constructor for Lumberjack::Logger and allows passing in a symbol to reference a
6
+ # formatter.
7
+ #
8
+ # Formatters must respond to the +call+ method.
9
+ #
10
+ # @example
11
+ #
12
+ # Lumberjack::FormatterRegistry.add(:upcase) { |value| value.to_s.upcase }
13
+ # Lumberjack::FormatterRegistry.add(:currency, Lumberjack::Formatter::RoundFormatter, 2)
14
+ #
15
+ # Lumberjack::EntryFormatter.build do |config|
16
+ # config.add_attribute :status, :upcase
17
+ # config.add_attribute :amount, :currency
18
+ # end
19
+ module FormatterRegistry
20
+ @registry = {}
21
+
22
+ class << self
23
+ # Register a formatter name. Formatter names can be used to associate a symbol with a formatter
24
+ # class. The symbol can then be passed to Logger as the formatter argument.
25
+ #
26
+ # Registered formatters must take only one argument and that is the options hash for the
27
+ # formatter options.
28
+ #
29
+ # @param name [Symbol] The name of the formatter
30
+ # @param formatter [Class, #call] The formatter or formatter class to register..
31
+ # @return [void]
32
+ def add(name, formatter = nil, &block)
33
+ raise ArgumentError.new("name must be a symbol") unless name.is_a?(Symbol)
34
+ raise ArgumentError.new("formatter or block must be provided") if formatter.nil? && block.nil?
35
+ raise ArgumentError.new("cannot have both formatter and a block") if !formatter.nil? && !block.nil?
36
+
37
+ formatter ||= block
38
+ raise ArgumentError.new("formatter must be a class or respond to call") unless formatter.is_a?(Class) || formatter.respond_to?(:call)
39
+
40
+ @registry[name] = formatter
41
+ end
42
+
43
+ # Remove a formatter from the registry.
44
+ #
45
+ # @param name [Symbol] The name of the formatter to remove
46
+ # @return [void]
47
+ def remove(name)
48
+ @registry.delete(name)
49
+ end
50
+
51
+ # Check if a formatter is registered.
52
+ #
53
+ # @param name [Symbol] The name of the formatter
54
+ # @return [Boolean] True if the formatter is registered, false otherwise
55
+ def registered?(name)
56
+ @registry.include?(name)
57
+ end
58
+
59
+ # Retrieve the formatter registered with the given name or nil if the name is not defined.
60
+ #
61
+ # @param name [Symbol] The name of the formatter
62
+ # @return [#call, nil] The registered formatter class or nil if not found
63
+ def formatter(name, *args)
64
+ instance = @registry[name]
65
+
66
+ if instance.nil?
67
+ valid_names = @registry.keys.map(&:inspect).join(", ")
68
+ raise ArgumentError.new("#{name.inspect} is not registered as a formatter name; valid names are: #{valid_names}")
69
+ end
70
+
71
+ instance = instance.new(*args) if instance.is_a?(Class)
72
+
73
+ instance
74
+ end
75
+
76
+ # Return the map of registered formatters.
77
+ #
78
+ # @return [Hash]
79
+ def registered_formatters
80
+ @registry.dup
81
+ end
82
+ end
83
+ end
84
+ end