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
data/README.md CHANGED
@@ -4,385 +4,778 @@
4
4
  [![Ruby Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://github.com/testdouble/standard)
5
5
  [![Gem Version](https://badge.fury.io/rb/lumberjack.svg)](https://badge.fury.io/rb/lumberjack)
6
6
 
7
- Lumberjack is a simple, powerful, and fast logging implementation in Ruby. It uses nearly the same API as the Logger class in the Ruby standard library and as ActiveSupport::BufferedLogger in Rails. It is designed with structured logging in mind, but can be used for simple text logging as well.
7
+ Lumberjack is an extension to the Ruby standard library `Logger` class, designed to provide advanced, flexible, and structured logging for Ruby applications. It builds on the familiar `Logger` API, adding powerful features for modern logging needs:
8
+
9
+ - **Attributes for Structured Logging:** Use attributes to attach structured, machine-readable metadata to log entries, enabling better filtering, searching, and analytics.
10
+ - **Context Isolation:** Isolate logging behavior to specific blocks of code. The attributes, level, and progname for the logger can all be changed in a context block and only impact the log messages created within that block.
11
+ - **Formatters:** Control how objects are logged with customizable formatters for messages and attributes.
12
+ - **Devices and Templates:** Choose from a variety of output devices and templates to define the format and destination of your logs.
13
+ - **Forked Loggers:** Create independent logger instances that inherit context from a parent logger, allowing for isolated logging configurations in different parts of your application.
14
+ - **Testing Tools:** Built-in testing devices and helpers make it easy to assert logging behavior in your test suite.
15
+
16
+ The philosophy behind the library is to promote use of structured logging with the standard Ruby Logger API as a foundation. The developer of a piece of functionality should only need to worry about the data that needs to be logged for that functionality and not how it is logged or formatted. Loggers can be setup with global attributes and formatters that handle these concerns.
17
+
18
+ ## Table of Contents
19
+
20
+ - [Usage](#usage)
21
+ - [Context Isolation](#context-isolation)
22
+ - [Context Blocks](#context-blocks)
23
+ - [Nested Context Blocks](#nested-context-blocks)
24
+ - [Forking Loggers](#forking-loggers)
25
+ - [Structured Logging With Attributes](#structured-logging-with-attributes)
26
+ - [Basic Attribute Logging](#basic-attribute-logging)
27
+ - [Adding attributes to the logger](#adding-attributes-to-the-logger)
28
+ - [Global Logger Attributes](#global-logger-attributes)
29
+ - [Nested Attributes and Complex Data](#nested-attributes-and-complex-data)
30
+ - [Attribute Inheritance and Merging](#attribute-inheritance-and-merging)
31
+ - [Working with Array Attributes](#working-with-array-attributes)
32
+ - [Formatters](#formatters)
33
+ - [Message Formatters](#message-formatters)
34
+ - [Attribute Formatters](#attribute-formatters)
35
+ - [Built-in Formatters](#built-in-formatters)
36
+ - [Custom Formatters](#custom-formatters)
37
+ - [Building An Entry Formatter](#building-an-entry-formatter)
38
+ - [Merging Formatters](#merging-formatters)
39
+ - [Devices and Templates](#devices-and-templates)
40
+ - [Built-in Devices](#built-in-devices)
41
+ - [Custom Devices](#custom-devices)
42
+ - [Templates](#templates)
43
+ - [Testing Utilities](#testing-utilities)
44
+ - [Using As A Stream](#using-as-a-stream)
45
+ - [Integrations](#integrations)
46
+ - [Installation](#installation)
47
+ - [Contributing](#contributing)
48
+ - [License](#license)
8
49
 
9
50
  ## Usage
10
51
 
11
- This code aims to be extremely simple to use and matches the standard Ruby `Logger` interface. The core interface is the Lumberjack::Logger which is used to log messages (which can be any object) with a specified Severity. Each logger has a level associated with it and messages are only written if their severity is greater than or equal to the level.
52
+ ### Context Isolation
53
+
54
+ Lumberjack provides context isolation that allow you to temporarily modify logging behavior for specific blocks of code or create independent logger instances. This is particularly useful for isolating logging configuration in different parts of your application without affecting the global logger state.
55
+
56
+ #### Context Blocks
57
+
58
+ Context blocks allow you to temporarily change the logger's configuration (level, progname, and attributes) for a specific block of code. When the block exits, the logger returns to its previous state.
59
+
60
+ Context blocks and forked loggers are thread and fiber-safe, maintaining isolation across concurrent operations:
12
61
 
13
62
  ```ruby
14
- logger = Lumberjack::Logger.new("logs/application.log") # Open a new log file with INFO level
15
- logger.info("Begin request")
16
- logger.debug(request.params) # Message not written unless the level is set to DEBUG
17
- begin
18
- # do something
19
- rescue => exception
20
- logger.error(exception)
21
- raise
22
- end
23
- logger.info("End request")
63
+ logger.level = :info
64
+
65
+ # Temporarily change log level for debugging a specific section
66
+ logger.context do
67
+ logger.level = :debug
68
+ logger.debug("This debug message will be logged")
69
+ end
70
+
71
+ # Back to info level - debug messages are filtered out again
72
+ logger.debug("This won't be logged")
24
73
  ```
25
74
 
26
- ## Features
75
+ You can use `with_level`, `with_progname`, and `tag` to setup a context block with a specific level, progname, or attributes.
27
76
 
28
- ### Metadata
77
+ As a best practice, every main unit of work in your application (i.e. HTTP request, background job, etc.) should have a context block. This ensures that any attributes or changes to the logger are scoped to that unit of work and do not leak into other parts of the application.
29
78
 
30
- When messages are added to the log, additional data about the message is kept in a Lumberjack::LogEntry. This means you don't need to worry about adding the time or process id to your log messages as they will be automatically recorded.
79
+ ##### Nested Context Blocks
31
80
 
32
- The following information is recorded for each message:
81
+ Context blocks can be nested, with inner contexts inheriting and potentially overriding outer context settings:
33
82
 
34
- - severity - The severity recorded for the message.
35
- - time - The time at which the message was recorded.
36
- - program name - The name of the program logging the message. This can be either set for all messages or customized with each message.
37
- - process id - The process id (pid) of the process that logged the message.
38
- - tags - A map of name value pairs for additional information about the log context.
83
+ ```ruby
84
+ logger.context do
85
+ logger.tag(user_id: 123, service: "api")
86
+ logger.info("API request started") # Includes user_id: 123, service: "api"
39
87
 
40
- ### Tags
88
+ logger.context(endpoint: "/users", service: "user_service") do
89
+ logger.tag(service: "user_service", endpoint: "/users")
90
+ logger.info("Processing user data") # Includes: user_id: 123, service: "user_service", endpoint: "/users"
91
+ end
41
92
 
42
- You can use tags to provide additional meta data about a log message or the context that the log message is being made in. Using tags can keep your log messages clean. You can avoid string interpolation to add additional meta data. Tags enable a structured logging approach where you can add additional information to log messages without changing the message format.
93
+ logger.info("API request completed") # Back to: user_id: 123, service: "api"
94
+ end
95
+ ```
96
+
97
+ #### Forking Loggers
43
98
 
44
- Each of the logger methods includes an additional argument that can be used to specify tags on a message:
99
+ Logger forking creates independent logger instances that inherit the parent logger's current context. Changes made to the forked logger will not affect the parent logger.
100
+
101
+ Forked loggers are useful when there is a section of your application that requires different logging behavior. Forked loggers are cheap to create, so you can use them liberally.
45
102
 
46
103
  ```ruby
47
- logger.info("request completed", duration: elapsed_time, status: response.status)
104
+ main_logger = Lumberjack::Logger.new
105
+ main_logger.tag!(version: "1.0.0")
106
+
107
+ # Create a forked logger for a specific component
108
+ user_service_logger = main_logger.fork(progname: "UserService", level: :debug)
109
+ user_service_logger.tag!(component: "user_management")
110
+
111
+ user_service_logger.debug("Debug info") # Includes version and component attributes
112
+ main_logger.info("Main logger info") # Includes only version attribute
113
+ main_logger.debug("Main logger debug info") # Not logged since level is :info
48
114
  ```
49
115
 
50
- You can also specify tags on a logger that will be included with every log message.
116
+ ### Structured Logging With Attributes
117
+
118
+ Lumberjack extends standard logging with **attributes** (structured key-value pairs) that add context and metadata to your log entries. This enables powerful filtering, searching, and analytics capabilities.
119
+
120
+ #### Basic Attribute Logging
121
+
122
+ Add attributes with any logging method:
51
123
 
52
124
  ```ruby
53
- logger.tag_globally(host: Socket.gethostname.force_encoding("UTF-8"))
125
+ # Add attributes to individual log calls
126
+ logger.info("User logged in", user_id: 123, ip_address: "192.168.1.100")
127
+ logger.error("Payment failed", user_id: 123, amount: 29.99, error: "card_declined")
128
+
129
+ # Attributes can be any type
130
+ logger.debug("Processing data",
131
+ records_count: 1500,
132
+ processing_time: 2.34,
133
+ metadata: { batch_id: "abc-123", source: "api" },
134
+ timestamp: Time.now
135
+ )
54
136
  ```
55
137
 
56
- You can specify tags that will only be applied to the logger in a block as well.
138
+ > [!Note]
139
+ > Attributes are passed in log statements in the little used `progname` argument that is defined in the standard Ruby Logger API. This attribute is normally used to set a specific program name for the log entry that overrides the default program name on the logger.
140
+ >
141
+ > The only difference in the API is that Lumberjack loggers can take a Hash to set attributes instead of just a string. You can still pass a string to override the program name.
142
+
143
+ #### Adding attributes to the logger
144
+
145
+ Use the `tag` method to tag the the current context with attributes. The attributes will be included in all log entries within that context.
57
146
 
58
147
  ```ruby
59
- logger.tag(thread_id: Thread.current.object_id) do
60
- logger.info("here") # Will include the `thread_id` tag
61
- logger.tag(count: 15)
62
- logger.info("with count") # Will include the `count` tag
148
+ logger.context do
149
+ logger.tag(user_id: current_user.id, session: "abc-def")
150
+ logger.info("Session started") # Includes user_id and session
151
+ logger.debug("Loading user preferences") # Includes user_id and session
152
+ logger.info("Dashboard rendered") # Includes user_id and session
63
153
  end
64
- logger.info("there") # Will not include the `thread_id` or `count` tag
154
+
155
+ logger.info("Outside of context") # Does not include user_id or session
65
156
  ```
66
157
 
67
- The block opens up a new tag context. The context applies only within a block and only for the currently executing thread. You can also open up a new context block without specifying any tags and then add tags to the context within the block.
158
+ You can also use the `tag` method with a block to open a new context and assign attributes.
68
159
 
69
160
  ```ruby
70
- logger.context do # When a block is given to `context`, it opens a new empty tag context.
71
- # `context` can be called without a block, to get an TagContext object for manipulating tags.
72
- logger.context.tag(user_id: current_user.id, username: current_user.username)
73
- logger.context["user_role"] = current_user.role # You can also use hash syntax to set tags.
74
- logger.info("user logged in") # Will include the `user_id`, `username`, and `user_role` tags.
161
+ # Apply attributes to all log entries within the block
162
+ logger.tag(user_id: 123, session: "abc-def") do
163
+ logger.info("Session started")
164
+ logger.debug("Loading user preferences")
165
+ logger.info("Dashboard rendered")
75
166
  end
76
- logger.info("no user") # Will not include the tags
77
167
  ```
78
168
 
79
- You can also set tags to `Proc` objects that will be evaluated when creating a log entry.
169
+ Calling `tag` outside of a context without a block is a no-op and has no effect on the logger.
170
+
171
+ You can also use the `tag_all_contexts` method to add attributes to all parent context blocks. This can be useful in cases where you need to set an attribute that should be included in all subsequent log entries for the duration of the process defined by the outermost context.
172
+
173
+ Consider this example where we want to include the `user_id` attribute in all log entries. We need to set it on all parent contexts in order to have it extend beyond the current context block.
80
174
 
81
175
  ```ruby
82
- logger.tag_globally(thread_id: lambda { Thread.current.object_id })
176
+ logger.context do
177
+ logger.tag(request_id: "req-123") do
178
+ logger.info("Processing request") # Includes request_id
83
179
 
84
- Thread.new do
85
- logger.info("inside thread") # Will include the `thread_id` tag with id of the spawned thread
86
- end
180
+ logger.tag(action: "login") do
181
+ user_id = login_user(params)
182
+
183
+ logger.tag(login_method: params[:login_method])
184
+ logger.tag_all_contexts(user_id: user_id)
87
185
 
88
- logger.info("outside thread") # Will include the `thread_id` tag with id of the main thread
186
+ logger.info("User logged in") # Includes request_id, action, login_method, and user_id
187
+ end
188
+
189
+ logger.info("Request completed") # Includes request_id and user_id
190
+ end
89
191
  ```
90
192
 
91
- Finally, you can specify a global logging context that applies to all loggers.
193
+ #### Global Logger Attributes
194
+
195
+ You can add global attributes that apply to all log entries with the `tag!` method.
92
196
 
93
197
  ```ruby
94
- Lumberjack.context do
95
- Lumberjack.tag(request_id: SecureRandom.hex) # add a global context tag
96
- logger.info("begin request") # Will include the `request_id` tag
97
- event_logger.info("http.request") # Will also include the `request_id` tag
98
- end
99
- logger.info("no requests") # Will not include the `request_id` tag
198
+ logger.tag!(
199
+ version: "1.2.3",
200
+ env: Rails.env,
201
+ request_id: -> { Current.request_id }
202
+ )
100
203
  ```
101
204
 
102
- Tag keys are always converted to strings. Tags are inherited so that message tags take precedence over block tags which take precedence over global tags.
205
+ If the value of an attribute is a `Proc`, it will be evaluated at runtime when the log entries are created. So in the above example, `request_id` will be dynamically set to the current request ID whenever a log entry is created.
103
206
 
104
- #### Structured Logging with Tags
207
+ Note that blank attributes are never included in the log output, so if `Current.request_id` is `nil`, the `request_id` attribute will be omitted from the log entry.
105
208
 
106
- Tags are particularly powerful for structured logging, where you want to capture machine-readable data alongside human-readable log messages. Instead of embedding variable data directly in log messages (which makes parsing difficult), you can use tags to separate the static message from the dynamic data.
209
+ There is also a global `Lumberjack` context that applies to all Lumberjack loggers.
107
210
 
108
211
  ```ruby
109
- # Instead of this (harder to parse)
110
- logger.info("User john_doe logged in from IP 192.168.1.100 in 0.25 seconds")
111
-
112
- # Do this (structured and parseable)
113
- logger.info("User logged in", {
114
- user_id: "john_doe",
115
- ip_address: "192.168.1.100",
116
- duration: 0.25,
117
- action: "login"
118
- })
212
+ Lumberjack.tag(version: "1.2.3") do
213
+ logger_1.info("Something happened") # Includes version
214
+ logger_2.info("Something else happened") # Includes version
215
+ end
119
216
  ```
120
217
 
121
- This approach provides several benefits:
122
-
123
- - **Consistent message format** - The base message stays the same while data varies
124
- - **Easy filtering and searching** - You can search by specific tag values
125
- - **Better analytics** - Aggregate data by tag values (e.g., average login duration)
126
- - **Machine processing** - Automated systems can easily extract and process tag data
218
+ #### Nested Attributes and Complex Data
127
219
 
128
- You can also use nested structures in tags for complex data:
220
+ Attributes support nested structures and complex data types:
129
221
 
130
222
  ```ruby
131
- logger.info("API request completed", {
223
+ logger.info("API request completed",
132
224
  request: {
133
225
  method: "POST",
134
226
  path: "/api/users",
135
- user_agent: request.user_agent
227
+ headers: { "Content-Type" => "application/json" }
136
228
  },
137
229
  response: {
138
230
  status: 201,
139
- duration_ms: 150
231
+ duration_ms: 45.2,
232
+ size_bytes: 1024
140
233
  },
141
234
  user: {
142
- id: current_user.id,
143
- role: current_user.role
235
+ id: 123,
236
+ role: "admin",
237
+ permissions: ["read", "write", "delete"]
144
238
  }
145
- })
239
+ )
146
240
  ```
147
241
 
148
- When combined with structured output devices (like [`lumberjack_json_device`](https://github.com/bdurand/lumberjack_json_device)), this creates logs that are both human-readable and machine-processable, making them ideal for log aggregation systems, monitoring, and analytics.
242
+ #### Attribute Inheritance and Merging
149
243
 
150
- #### Compatibility with ActiveSupport::TaggedLogging
244
+ Attributes from different sources are merged together, with more specific attributes taking precedence:
151
245
 
152
- `Lumberjack::Logger` is compatible with `ActiveSupport::TaggedLogging`. This is so that other code that expects to have a logger that responds to the `tagged` method will work. Any tags added with the `tagged` method will be appended to an array in the "tagged" tag.
246
+ ```ruby
247
+ # Persistent logger attributes
248
+ logger.tag!(service: "web", datacenter: "us-east-1")
249
+
250
+ logger.tag(request_id: "req-123") do
251
+ # Block-level attributes override any conflicts
252
+ logger.tag(datacenter: "us-west-2") do
253
+ logger.info("Processing request",
254
+ user_id: 456,
255
+ datacenter: "eu-central-1" # This takes highest precedence
256
+ )
257
+ # Final attributes: { service: "web", request_id: "req-123", user_id: 456, datacenter: "eu-central-1" }
258
+ end
259
+ end
260
+ ```
261
+
262
+ Attributes use dot notation for nested structures, so there is no difference between these statements:
153
263
 
154
264
  ```ruby
155
- logger.tagged("foo", "bar=1", "other") do
156
- logger.info("here") # will include tags: {"tagged" => ["foo", "bar=1", "other"]}
265
+ logger.info("User signed in", user: {id: 123})
266
+ logger.info("User signed in", "user.id" => 123)
267
+ ```
268
+
269
+ #### Working with Array Attributes
270
+
271
+ A common practice is to add an array of values to a specific attribute. You can use the `append_to` method to append values to an array attribute in the current context. Like the `tag` method, this method can be called with a block to create a new context or without a block to update the current context.
272
+
273
+ ```ruby
274
+ logger.append_to(:tags, "api", "v1") do
275
+ logger.info("API request started") # Includes tags: ["api", "v1"]
276
+
277
+ logger.append_to(:tags, "users")
278
+ logger.info("Processing user data") # Includes tags: ["api", "v1", "users"]
279
+ end
280
+
281
+ # You can also append to other array attributes
282
+ logger.append_to(:categories, "billing", "premium") do
283
+ logger.info("Processing premium billing") # Includes categories: ["billing", "premium"]
157
284
  end
158
285
  ```
159
286
 
160
- #### Templates
287
+ ### Formatters
288
+
289
+ Lumberjack provides a powerful formatting system that controls how objects are converted to strings in log entries. With this feature you can pass objects to the logger and rely on the formatters to handle formatting thereby simplifying the logging code and improving consistency.
290
+
291
+ There are two types of formatters.
292
+
293
+ #### Message Formatters
294
+
295
+ Message formatters control how different types of objects are converted to strings when logged as messages. Message formatters are registered for specific classes or modules. When you log an object, the formatter will be looked up based on the object's class.
296
+
297
+ ```ruby
298
+ logger.formatter.format_message(Array) { |arr| arr.join(", ") }
299
+
300
+ logger.info([1, 2, 3]) # Logs "1, 2, 3"
301
+ ```
161
302
 
162
- The built in `Lumberjack::Device::Writer` class has built in support for including tags in the output using the `Lumberjack::Template` class.
303
+ For log messages you can use the `Lumberjack::MessageAttributes` class to extract structured data from a log message. This can be used to allow logging objects directly and extracting metadata from the objects in the log attributes.
163
304
 
164
- You can specify any tag name you want in a template as well as the `:tags` macro for all tags. If a tag name has been used as its own macro, it will not be included in the `:tags` macro.
305
+ ```ruby
306
+ logger.formatter.format_message(Exception) do |error|
307
+ Lumberjack::MessageAttributes.new(
308
+ error.inspect, # This will be used as the log message
309
+ error: { # This will be added to the log attributes
310
+ type: error.class.name,
311
+ message: error.message,
312
+ backtrace: error.backtrace
313
+ }
314
+ )
315
+ end
316
+
317
+ # This will now log the message as `exception.inspect` and pull
318
+ # out the type, message, and backtrace into attributes. With this
319
+ # you won't need to figure out how to log each exception and just
320
+ # just log the object itself and let the formatter deal with it.
321
+ logger.error(exception)
322
+ ```
323
+
324
+ #### Attribute Formatters
325
+
326
+ Attribute formatters control how attribute values (the key-value pairs in structured logging) are formatted. They provide fine-grained control over different attributes and data types.
327
+
328
+ You can specify how to format object types when they are logged as attributes:
329
+
330
+ ```ruby
331
+ logger.formatter.format_attributes(Time, :date_time, "%Y-%m-%d %H:%M:%S")
332
+ logger.formatter.format_attributes([Float, BigDecimal], :round, 2)
333
+
334
+ logger.info("Data processed",
335
+ created_at: Time.now, # → "2025-08-22 14:30:00"
336
+ price: 29.099, # → 29.10
337
+ )
338
+ ```
165
339
 
166
- ### Pluggable Devices
340
+ You can also format attributes based on the attribute name:
167
341
 
168
- When a Logger logs a LogEntry, it sends it to a Lumberjack::Device. Lumberjack comes with a variety of devices for logging to IO streams or files.
342
+ ```ruby
343
+ # Configure attribute formatting
344
+ logger.formatter.format_attribute_name("password") { |pwd| "[REDACTED]" }
345
+ logger.formatter.format_attribute_name("email") { |email| email.downcase }
346
+ logger.formatter.format_attribute_name("cost", :round, 2)
347
+
348
+ # Now attributes are formatted according to the rules
349
+ logger.info("User created",
350
+ email: "JOHN@EXAMPLE.COM", # → "john@example.com"
351
+ password: "secret123", # → "[REDACTED]"
352
+ cost: 29.129999 # → 29.13
353
+ )
354
+ ```
169
355
 
170
- - Lumberjack::Device::Writer - Writes log entries to an IO stream.
171
- - Lumberjack::Device::LogFile - Writes log entries to a file.
172
- - Lumberjack::Device::DateRollingLogFile - Writes log entries to a file that will automatically roll itself based on date.
173
- - Lumberjack::Device::SizeRollingLogFile - Writes log entries to a file that will automatically roll itself based on size.
174
- - Lumberjack::Device::Multi - This device wraps multiple other devices and will write log entries to each of them.
175
- - Lumberjack::Device::Null - This device produces no output and is intended for testing environments.
356
+ You can remap attributes to other attribute names by returning a `Lumberjack::RemapAttribute` instance.
176
357
 
177
- If you'd like to send your log to a different kind of output, you just need to extend the Device class and implement the `write` method. Or check out these plugins:
358
+ ```ruby
359
+ # Move the email attribute under the user attributes.
360
+ logger.formatter.format_attribute_name("email") do |value|
361
+ Lumberjack::RemapAttribute.new("user.email" => value)
362
+ end
363
+
364
+ # Transform duration_millis and duration_micros to seconds and move to
365
+ # the duration attribute.
366
+ logger.formatter.format_attribute_name("duration_ms") do |value|
367
+ Lumberjack::RemapAttribute.new("duration" => value.to_f / 1000)
368
+ end
369
+ logger.formatter.format_attribute_name("duration_micros") do |value|
370
+ Lumberjack::RemapAttribute.new("duration" => value.to_f / 1_000_000)
371
+ end
372
+ ```
178
373
 
179
- - [lumberjack_json_device](https://github.com/bdurand/lumberjack_json_device) - output your log messages as stream of JSON objects for structured logging.
180
- - [lumberjack_syslog_device](https://github.com/bdurand/lumberjack_syslog_device) - send your log messages to the system wide syslog service
181
- - [lumberjack_mongo_device](https://github.com/bdurand/lumberjack_mongo_device) - store your log messages to a [MongoDB](http://www.mongodb.org/) NoSQL data store
182
- - [lumberjack_redis_device](https://github.com/bdurand/lumberjack_redis_device) - store your log messages in a [Redis](https://redis.io/) data store
183
- - [lumberjack-couchdb-driver](https://github.com/narkisr/lumberjack-couchdb-driver) - store your log messages to a [CouchDB](http://couchdb.apache.org/) NoSQL data store
184
- - [lumberjack_heroku_device](https://github.com/tonycoco/lumberjack_heroku_device) - log to Heroku's logging system
185
- - [lumberjack_capture_device](https://github.com/bdurand/lumberjack_capture_device) - capture log messages in memory in test environments so that you can include log output assertions in your tests.
374
+ Finally, you can add a default formatter for all other attributes:
186
375
 
187
- ### Customize Formatting
376
+ ```ruby
377
+ logger.formatter.default_attribute_format { |value| value.to_s.strip[0..100] }
378
+ ```
188
379
 
189
- #### Formatters
380
+ #### Built-in Formatters
190
381
 
191
- The message you send to the logger can be any object type and does not need to be a string. You can specify how to format different object types with a formatter. The formatter is responsible for converting the object into a string representation for logging. You do this by mapping classes or modules to formatter code. This code can be either a block or an object that responds to the `call` method. The formatter will be called with the object logged as the message and the returned value will be what is sent to the device.
382
+ Lumberjack provides several predefined formatters that can be referenced by symbol:
192
383
 
193
384
  ```ruby
194
- # Format all floating point numbers with three significant digits.
195
- logger.formatter.add(Float) { |value| value.round(3) }
385
+ logger = Lumberjack::Logger.new
386
+
387
+ # Configure the formatter
388
+ logger.formatter.format_class(Float, :round, 2) # Round floats to 2 decimals
389
+ logger.formatter.format_class(Time, :date_time, "%H:%M") # Custom time format
196
390
 
197
- # Format all enumerable objects as a comma delimited string.
198
- logger.formatter.add(Enumerable) { |value| value.join(", ") }
391
+ # Now these objects will be formatted according to the rules
392
+ logger.info(3.14159) # "3.14"
393
+ logger.info(Time.now) # "14:30"
199
394
  ```
200
395
 
201
- There are several built in classes you can add as formatters. You can use a symbol to reference built in formatters.
396
+ **Available Built-in Formatters:**
397
+
398
+ | Formatter | Purpose |
399
+ |-----------|---------|
400
+ | `:date_time` | Format time/date objects |
401
+ | `:exception` | Format exceptions with stack traces |
402
+ | `:id` | Extract object ID or specified field |
403
+ | `:inspect` | Use Ruby's inspect method |
404
+ | `:multiply` | Multiply numeric values |
405
+ | `:object` | Generic object formatter |
406
+ | `:pretty_print` | Pretty print using PP library |
407
+ | `:redact` | Redact sensitive information |
408
+ | `:round` | Round numeric values |
409
+ | `:string` | Convert to string using to_s |
410
+ | `:strip` | Strip whitespace from strings |
411
+ | `:structured` | Recursively format collections |
412
+ | `:tags` | Format values as tags in the format "[val1] [val2]" for arrays or "[key=value]" for hashes |
413
+ | `:truncate` | Truncate long strings |
414
+
415
+ #### Custom Formatters
416
+
417
+ You can create custom formatters using blocks, callable objects, or custom classes:
202
418
 
203
419
  ```ruby
204
- logger.formatter.add(Hash, :pretty_print) # use the Formatter::PrettyPrintFormatter for all Hashes
205
- logger.formatter.add(Hash, Lumberjack::Formatter::PrettyPrintFormatter.new) # alternative using a formatter instance
420
+ # Block-based formatters
421
+ logger.formatter.format_class(User) { |user| "User[#{user.id}:#{user.name}]" }
422
+ logger.formatter.format_class(BigDecimal) { |decimal| "$#{decimal.round(2)}" }
423
+
424
+ # Callable object formatters
425
+ class TimeFormatter
426
+ def call(time)
427
+ time.strftime("%Y-%m-%d %H:%M:%S")
428
+ end
429
+ end
430
+
431
+ logger.formatter.format_class(SecureString, PasswordFormatter.new)
206
432
  ```
207
433
 
208
- - `:object` - `Lumberjack::Formatter::ObjectFormatter` - no op conversion that returns the object itself.
209
- - `:string` - `Lumberjack::Formatter::StringFormatter` - calls `to_s` on the object.
210
- - `:strip` - `Lumberjack::Formatter::StripFormatter` - calls `to_s.strip` on the object.
211
- - `:inspect` - `Lumberjack::Formatter::InspectFormatter` - calls `inspect` on the object.
212
- - `:exception` - `Lumberjack::Formatter::ExceptionFormatter` - special formatter for exceptions which logs them as multi-line statements with the message and backtrace.
213
- - `:date_time` - `Lumberjack::Formatter::DateTimeFormatter` - special formatter for dates and times to format them using `strftime`.
214
- - `:pretty_print` - `Lumberjack::Formatter::PrettyPrintFormatter` - returns the pretty print format of the object.
215
- - `:id` - `Lumberjack::Formatter::IdFormatter` - returns a hash of the object with keys for the id attribute and class.
216
- - `:structured` - `Lumberjack::Formatter::StructuredFormatter` - crawls the object and applies the formatter recursively to Enumerable objects found in it (arrays, hashes, etc.).
217
- - `:truncate` - `Lumberjack::Formatter::TruncateFormatter` - truncates long strings to a specified length.
434
+ Classes can also implement `to_log_format` to define how instances should be serialized for logging. This will apply to both message and attribute formatting.
218
435
 
219
- To define your own formatter, either provide a block or an object that responds to `call` with a single argument.
436
+ ```ruby
437
+ class User
438
+ attr_accessor :id, :name
220
439
 
221
- #### Default Formatter
440
+ def to_log_format
441
+ "User[id: #{ id }, name: #{ name }]"
442
+ end
443
+ end
444
+ ```
222
445
 
223
- The default formatter is applied to all objects being logged. This includes both messages and tags.
446
+ Primitive classes (`String`, `Integer`, `Float`, `TrueClass`, `FalseClass`, `NilClass`, `BigDecimal`) will not use `to_log_format`.
224
447
 
225
- The default formatter will pass through values for strings, numbers, and booleans, and use the `:inspect` formatter for all objects except for exceptions which will be formatted with the `:exception` formatter.
448
+ #### Building An Entry Formatter
226
449
 
227
- #### Message Formatter
450
+ The Entry Formatter coordinates both message and attribute formatting, providing a unified configuration interface:
228
451
 
229
- You can add a formatter for just the log message with the `message_formatter` method. This formatter will only apply to the message and not to any tags.
452
+ ##### Complete Entry Formatter Setup
230
453
 
231
454
  ```ruby
232
- logger.message_formatter.add(String, :truncate, 1000) # Will truncate all string messages to 1000 characters
455
+ # Build a comprehensive entry formatter
456
+ entry_formatter = Lumberjack.build_formatter do |formatter|
457
+ # Format for ActiveRecord models that applies to both messages and attributes.
458
+ formatter.format_class(ActiveRecord::Base, :id)
459
+
460
+ # Format for the User class when it is logged as the log message.
461
+ formatter.format_message(User) { |user| "User[#{user.id}:#{user.username}]" }
462
+
463
+ # Attribute formatting
464
+ formatter.format_attributes(Time, :date_time, "%Y-%m-%d %H:%M:%S")
465
+ formatter.format_attributes([Float, BigDecimal], :round, 6)
466
+ formatter.format_attribute_name("email", :redact)
467
+ end
468
+
469
+ # Use with logger
470
+ logger = Lumberjack::Logger.new(STDOUT, formatter: entry_formatter)
233
471
  ```
234
472
 
235
- ##### Extracting Tags from Messages
473
+ #### Merging Formatters
236
474
 
237
- If you are using structured logging, you can use a formatter to extract tags from the log message by adding a formatter that returns a `Lumberjack::Formatter::TaggedMessage`. For example, if you want to extract metadata from exceptions and add them as tags, you could do this:
475
+ You can merge other formatters into your formatter with the `include` method. Doing so will copy all of the format definitions.
238
476
 
239
477
  ```ruby
240
- logger.message_formatter.add(Exception, ->(e) {
241
- Lumberjack::Formatter::TaggedMessage.new(e.inspect, {
242
- "error.message": e.message,
243
- "error.class": e.class.name,
244
- "error.trace": e.backtrace
245
- })
246
- })
478
+ # Translate the duration tag to microseconds.
479
+ duration_formatter = Lumberjack::EntryFormatter.build do |formatter|
480
+ formatter.format_attribute_name(:duration) { |seconds| (seconds.to_f * 1_000_000).round }
481
+ end
247
482
 
248
- logger.error(exception) # Will log the exception and add tags for the message, class, and trace.
483
+ entry_formatter = Lumberjack::EntryFormatter.build do |formatter|
484
+ # Adds the duration attribute formatter
485
+ formatter.include(duration_formatter)
486
+ end
249
487
  ```
250
488
 
251
- #### Tag Formatters
489
+ You can also call `prepend` in which case any formats already defined will take precedence over the formats being included.
490
+
491
+ ### Devices and Templates
492
+
493
+ Devices control where and how log entries are written. Lumberjack provides a variety of built-in devices that can write to files, streams, multiple destinations, or serve special purposes like testing. All devices implement a common interface, making them interchangeable.
494
+
495
+ #### Built-in Devices
252
496
 
253
- The `logger.formatter` will only apply to log messages. You can use `logger.tag_formatter` to register formatters for tags. You can register both default formatters that will apply to all tag values, as well as tag specific formatters that will apply only to objects with a specific tag name.
497
+ ##### Writer Device
254
498
 
255
- The formatter values can be either a `Lumberjack::Formatter` or a block or an object that responds to `call`. If you supply a `Lumberjack::Formatter`, the tag value will be passed through the rules for that formatter. If you supply a block or other object, it will be called with the tag value.
499
+ The `Writer` device is the foundation for most logging output, writing formatted log entries to any IO stream. It will be used if you pass an IO object to the logger.
256
500
 
257
501
  ```ruby
258
- # These will all do the same thing formatting all tag values with `inspect`
259
- logger.tag_formatter.default(Lumberjack::Formatter.new.clear.add(Object, :inspect))
260
- logger.tag_formatter.default(Lumberjack::Formatter::InspectFormatter.new)
261
- logger.tag_formatter.default { |value| value.inspect }
502
+ logger = Lumberjack::Logger.new(STDOUT)
503
+ ```
504
+
505
+ ##### LogFile Device
506
+
507
+ The `LogFile` device handles logging to a file. It has the same log rotation capabilities as the `Logger::LogDevice` class in the standard library logger.
262
508
 
263
- # This will register formatters only on specific tag names
264
- logger.tag_formatter.add(:thread) { |thread| "Thread(#{thread.name})" }
265
- logger.tag_formatter.add(:current_user, Lumberjack::Formatter::IdFormatter.new)
509
+ ```ruby
510
+ # Daily log rotation
511
+ logger = Lumberjack::Logger.new("/var/log/app.log", 'daily')
512
+ ```
266
513
 
267
- # You can also register formatters for tag values by class
268
- logger.tag_formatter.add(Numeric, &:round)
514
+ ##### Multi Device
269
515
 
270
- # Tag formatters will be applied to nested hashes and arrays as well.
516
+ The `Multi` device broadcasts log entries to multiple devices simultaneously. You can instantiate a multi device by passing in an array of values.
271
517
 
272
- # Name formatters use dot syntax to apply to nested hashes.
273
- logger.tag_formatter.add("user.username", &:upcase)
274
- # logger.tag(user: {username: "john_doe"}) # Will log the tag as {"user" => "username" => "JOHN_DOE"}
518
+ ```ruby
519
+ # Log to both file and STDOUT; the logs to STDOUT will only contain the log message.
520
+ logger = Lumberjack::Logger.new(["/var/log/app.log", [:stdout, {template: "{{message}}"}]])
521
+
522
+ logger.info("Application started") # Appears in both file AND STDOUT
275
523
  ```
276
524
 
277
- #### Templates
525
+ ##### LoggerWrapper Device
526
+
527
+ The `LoggerWrapper` device forwards entries to another Logger instance. It is most useful when you want to route logs from one logger to another, possibly with different configurations.
278
528
 
279
- If you use the built-in `Lumberjack::Device::Writer` derived devices, you can also customize the Template used to format the LogEntry.
529
+ ```ruby
530
+ target_logger = Lumberjack::Logger.new("/var/log/target.log")
531
+ logger = Lumberjack::Logger.new(target_logger)
532
+ ```
533
+
534
+ > [!NOTE]
535
+ > Note that the level of the outer logger will take precedence. So if the outer logger is set to `:warn`, then only warning messages or higher will be forwarded to the target logger.
536
+
537
+ > [!TIP]
538
+ > You can also pass in a standard Ruby `Logger` instance. This allows you to use the enhanced Lumberjack logging features with a standard library logger.
539
+
540
+ ##### Test Device
280
541
 
281
- See `Lumberjack::Template` for a complete list of macros you can use in the template. You can also use a block that receives a `Lumberjack::LogEntry` as a template.
542
+ The `Test` device logs entries in memory and is intended for use in test suites where you want to make assertions that specific log entries are recorded.
282
543
 
283
544
  ```ruby
284
- # Change the format of the time in the log
285
- Lumberjack::Logger.new("application.log", :time_format => "%m/%d/%Y %H:%M:%S")
545
+ logger = Lumberjack::Logger.new(:test)
546
+ ```
547
+
548
+ > [!TIP]
549
+ > See the [testing utilities](#testing-utilities) section for more information.
286
550
 
287
- # Use a simple template that only includes the time and the message
288
- Lumberjack::Logger.new("application.log", :template => ":time - :message")
551
+ ##### Null Device
289
552
 
290
- # Use a simple template that includes tags, but handles the `duration` tag separately.
291
- # All tags will appear at the end of the message except for `duration` which will be at the beginning.
292
- Lumberjack::Logger.new("application.log", :template => ":time (:duration) - :message - :tags")
553
+ The `Null` device discards all output.
293
554
 
294
- # Use a custom template as a block that only includes the first character of the severity
295
- template = lambda{|e| "#{e.severity_label[0, 1]} #{e.time} - #{e.message}"}
296
- Lumberjack::Logger.new("application.log", :template => template)
555
+ ```ruby
556
+ logger = Lumberjack::Logger.new(:null)
297
557
  ```
298
558
 
299
- ### Buffered Logging
559
+ #### Custom Devices
300
560
 
301
- The logger has hooks for devices that support buffering to potentially increase performance by batching physical writes. Log entries are not guaranteed to be written until the Lumberjack::Logger#flush method is called. Buffering can improve performance if I/O is slow or there is high overhead writing to the log device.
561
+ You can create custom devices by implementing the `write` method. The `write` method will receive a `Lumberjack::LogEntry` object and is free to process it in any way.
302
562
 
303
- You can use the `:flush_seconds` option on the logger to periodically flush the log. This is usually a good idea so you can more easily debug hung processes. Without periodic flushing, a process that hangs may never write anything to the log because the messages are sitting in a buffer. By turning on periodic flushing, the logged messages will be written which can greatly aid in debugging the problem.
563
+ ```ruby
564
+ class DatabaseDevice < Lumberjack::Device
565
+ def initialize(database_connection)
566
+ @db = database_connection
567
+ end
568
+
569
+ def write(entry)
570
+ @db.execute(
571
+ "INSERT INTO logs (timestamp, level, message, attributes, pid) VALUES (?, ?, ?, ?, ?)",
572
+ entry.time,
573
+ entry.severity_label,
574
+ entry.message,
575
+ JSON.generate(entry.attributes),
576
+ entry.pid
577
+ )
578
+ end
579
+
580
+ def close
581
+ @db.close
582
+ end
583
+ end
584
+
585
+ # Usage
586
+ db_device = DatabaseDevice.new(SQLite3::Database.new("logs.db"))
587
+ logger = Lumberjack::Logger.new(db_device)
588
+ ```
589
+
590
+ There are separate gems implementing custom devices for different use cases:
304
591
 
305
- The built in stream based logging devices use an internal buffer. The size of the buffer (in bytes) can be set with the `:buffer_size` options when initializing a logger. The default behavior is to not buffer.
592
+ - [lumberjack_json_device](https://github.com/bdurand/lumberjack_json_device) - Output logs to JSON
593
+ - [lumberjack_datadog_device](https://github.com/bdurand/lumberjack_datadog) - Output logs in JSON using the Datadog standard attributes.
594
+ - [lumberjack_capture_device](https://github.com/bdurand/lumberjack_capture_device) - Device designed for capturing logs in tests to make assertions easier
595
+ - [lumberjack_syslog_device](https://github.com/bdurand/lumberjack_syslog_device) - Device for logging to a syslog server
596
+ - [lumberjack_redis_device](https://github.com/bdurand/lumberjack_redis_device) - Device for logging to a Redis database
597
+
598
+ You can register a custom device with Lumberjack using the device registry. This associates the device with the device class and can make using the device easier to setup since the user can pass the symbol and options when instantiating the Logger rather than having to instantiate the device separately.
306
599
 
307
600
  ```ruby
308
- # Set buffer to flush after 8K has been written to the log.
309
- logger = Lumberjack::Logger.new("application.log", :buffer_size => 8192)
601
+ Lumberjack::Device.register(:my_device, MyDevice)
310
602
 
311
- # Turn off buffering so entries are immediately written to disk.
312
- logger = Lumberjack::Logger.new("application.log", :buffer_size => 0)
603
+ # Now logger can be instantiated with the name and all options will be passed to
604
+ # the MyDevice constructor.
605
+ logger = Lumberjack::Logger.new(:my_device, autoflush: true)
313
606
  ```
314
607
 
315
- ### Automatic Log Rolling
608
+ #### Templates
316
609
 
317
- The built in devices include two that can automatically roll log files based either on date or on file size. When a log file is rolled, it will be renamed with a suffix and a new file will be created to receive new log entries. This can keep your log files from growing to unusable sizes and removes the need to schedule an external process to roll the files.
610
+ The output devices writing to a stream or file can define templates that formats how log entries are written. Templates use mustache-style placeholders that are replaced with values from the log entry.
318
611
 
319
- There is a similar feature in the standard library Logger class, but the implementation here is safe to use with multiple processes writing to the same log file.
612
+ ##### Basic Template Usage
320
613
 
321
- ## Integrations
614
+ ```ruby
615
+ # Simple template with common fields
616
+ logger = Lumberjack::Logger.new(STDOUT, template: "{{time}} {{severity}} {{message}}")
322
617
 
323
- Lumberjack has built in support for logging extensions in Rails.
618
+ logger.info("Application started")
619
+ # Output: 2025-09-03T14:30:15.123456 INFO Application started
620
+ ```
324
621
 
325
- You can use the [`lumberjack_sidekiq`](https://github.com/bdurand/lumberjack_sidekiq) gem to replace Sidekiq's default logger with Lumberjack. This allows you to use all of Lumberjack's features, such as structured logging and tag support, in your Sidekiq jobs.
622
+ ##### Available Template Variables
326
623
 
327
- If you are using DataDog for logging, you can use the [`lumberjack_data_dog`](https://github.com/bdurand/lumberjack_data_dog) gem to format your logs in DataDog's standard attributes format.
624
+ Templates support the following placeholder variables:
328
625
 
329
- ## Differences from Standard Library Logger
626
+ | Variable | Description |
627
+ |----------|-------------|
628
+ | `time` | Timestamp |
629
+ | `severity` | Severity level |
630
+ | `progname` | Program name |
631
+ | `pid` | Process ID |
632
+ | `message` | Log message |
633
+ | `attributes` | Formatted attributes |
330
634
 
331
- `Lumberjack::Logger` does not extend from the `Logger` class in the standard library, but it does implement a compatible API. The main difference is in the flow of how messages are ultimately sent to devices for output.
635
+ In addition you can put any attribute name in a placeholder. The attribute will be inserted in the log line where the placeholder is defined and will be removed from the general list of attributes.
332
636
 
333
- The standard library Logger logic converts the log entries to strings and then sends the string to the device to be written to a stream. Lumberjack, on the other hand, sends structured data in the form of a `Lumberjack::LogEntry` to the device and lets the device worry about how to format it. The reason for this flip is to better support structured data logging. Devices (even ones that write to streams) can format the entire payload including non-string objects and tags however they need to.
637
+ ```ruby
638
+ # The user_id attribute will appear separately on the log line from the
639
+ # rest of the attributes.
640
+ logger = Lumberjack::Logger.new(STDOUT,
641
+ template: "[{{time}} {{severity}} {{user_id}}] {{message}} {{attributes}}"
642
+ )
643
+ ```
334
644
 
335
- The logging methods (`debug`, `info`, `warn`, `error`, `fatal`) are overloaded with an additional argument for setting tags on the log entry.
645
+ The severity can also have an optional formatting argument added to it.
336
646
 
337
- ## Examples
647
+ | Variable | Description |
648
+ |----------|-------------|
649
+ | `severity` | Uppercase case severity label (INFO, WARN, etc.) |
650
+ | `severity(padded)` | Severity label padded to 5 characters |
651
+ | `severity(char)` | First character of severity label |
652
+ | `severity(emoji)` | Emoji representation of severity level |
653
+ | `severity(level)` | Numeric severity level |
338
654
 
339
- These examples are for Rails applications, but there is no dependency on Rails for using this gem. Most of the examples are applicable to any Ruby application.
655
+ ##### Template Options
340
656
 
341
- In a Rails application you can replace the default production logger by adding this to your config/environments/production.rb file:
657
+ You can customize how template variables are formatted using template options:
342
658
 
343
659
  ```ruby
344
- # Add the ActionDispatch request id as a global tag on all log entries.
345
- config.middleware.insert_after(
346
- ActionDispatch::RequestId,
347
- Lumberjack::Rack::Context,
348
- request_id: ->(env) { env["action_dispatch.request_id"] }
349
- )
350
- # Change the logger to use Lumberjack
351
- log_file = Rails.root + "log" + "#{Rails.env}.log"
352
- # log_file = $stdout # or write to stdout instead of a file
353
- config.logger = Lumberjack::Logger.new(log_file, :level => :warn)
660
+ logger = Lumberjack::Logger.new(STDOUT,
661
+ template: "[{{time}} {{severity(padded)}} {{progname}}({{pid}})] [{{http.request_id}}] {{message}} {{attributes}}",
662
+ time_format: "%Y-%m-%d %H:%M:%S", # Custom time format
663
+ additional_lines: "\n> [{{http.request_id}}] {{message}}", # Template for additional lines on multiline messages
664
+ attribute_format: "[%s=%s]", # Format for attributes using printf syntax
665
+ colorize: true # Colorize log output according to entry severity
666
+ )
667
+
668
+ logger.info("Test message", user_id: 123, status: "active")
669
+ # Output: 2025-09-03 14:30:15 INFO Test message [user_id=123] [status=active]
354
670
  ```
355
671
 
356
- To set up a logger to roll every day at midnight, you could use this code (you can also specify :weekly or :monthly):
672
+ ##### Built-in Templates
673
+
674
+ You can use symbols to refer to built-in templates:
675
+
676
+ - `:default` - The default log template. This is the same as not specifying a template.
677
+ - `:stdlib` - A template that mimics the default format of the standard library Logger.
678
+ - `:local` - A simple, human readable template intended for local development and test environments. This template removes the time and pid from the log line since they are generally not needed in these environments. You can also exclude attributes by setting the `exclude_attributes` option to the list of attributes names to exclude. For example, you may want to add a `host` attribute for your production logs, but this just creates clutter in development logs since it is always the same value.
357
679
 
358
680
  ```ruby
359
- config.logger = Lumberjack::Logger.new(log_file_path, :roll => :daily)
681
+ logger = Lumberjack::Logger.new(STDOUT, template: :local, exclude_attributes: ["host", "env", "version"])
360
682
  ```
361
683
 
362
- To set up a logger to roll log files when they get to 100Mb, you could use this:
684
+ ### Testing Utilities
685
+
686
+ The `Test` device captures log entries in memory for testing and assertions:
363
687
 
364
688
  ```ruby
365
- config.logger = Lumberjack::Logger.new(log_file_path, :max_size => 100.megabytes)
689
+ logger = Lumberjack::Logger.new(:test)
690
+
691
+ # Log some entries
692
+ logger.info("User logged in", user_id: 123)
693
+ logger.error("Payment failed", amount: 29.99)
694
+
695
+ # You can make assertions against the logs (using rspec in this case)
696
+ expect(logger.device.entries.size).to eq(2)
697
+ expect(logger.device.last_entry.message).to eq("Payment failed")
698
+
699
+ # Use pattern matching
700
+ expect(logger.device).to include(
701
+ severity: :info,
702
+ message: "User logged in",
703
+ attributes: { user_id: 123 }
704
+ )
705
+
706
+ expect(logger.device).to include(severity: :error, message: /Payment/)
366
707
  ```
367
708
 
368
- To change the log message format, you could use this code:
709
+ You should make sure to call `logger.device.clear` between tests to clear the captured logs on any global loggers that are using the `Test` device.
710
+
711
+ > [!NOTE]
712
+ > Log entries are captured after formatters have been applied. This provides a mechanism for including the formatting logic in your tests.
713
+
714
+ > [!TIP]
715
+ > The [lumberjack_capture_device](https://github.com/bdurand/lumberjack_capture_device) gem provides some additional testing utilities and rspec integration.
716
+
717
+ You can also use the `write_to` method on the `Test` device to write the captured log entries to another logger or device. This can be useful in scenarios where you want to preserve log output for failed tests.
369
718
 
370
719
  ```ruby
371
- config.logger = Lumberjack::Logger.new(log_file_path, :template => ":time - :message")
720
+ # Set up test logger (presumably in an initializer)
721
+ Application.logger = Lumberjack::Logger.new(:test)
722
+
723
+ # Hook into your test framework; in this example using rspec.
724
+ RSpec.configure do |config|
725
+ failed_test_logs = Lumberjack::Logger.new("log/test_failures.log")
726
+ config.around do |example|
727
+ # Clear the captured logs so we start with a clean slate.
728
+ Application.logger.clear
729
+
730
+ example.run
731
+
732
+ if example.exception
733
+ failed_test_logs.error("Test failed: #{example.full_description} @ #{example.location}")
734
+ Application.logger.device.write_to(failed_test_logs)
735
+ end
736
+ end
737
+ end
372
738
  ```
373
739
 
374
- To change the log message format to output JSON, you could use this code:
740
+ Lumberjack will catch any errors raised when logging and output the error message and backtrace to STDERR. This prevents logging errors from crashing your application. You should disable this behavior in your test suite so that logging errors are raised and can be fixed.
375
741
 
376
742
  ```ruby
377
- config.logger = Lumberjack::Logger.new(log_file_path, :template => lambda{|e| JSON.dump(time: e.time, level: e.severity_label, message: e.message)})
743
+ Lumberjack.raise_logging_errors = true
378
744
  ```
379
745
 
380
- To send log messages to syslog instead of to a file, you could use this (requires the lumberjack_syslog_device gem):
746
+ ### Using As A Stream
747
+
748
+ Lumberjack loggers implement methods necessary for treating them like a stream. You can use this to augment output from components that write output to a stream with metadata like a timestamp and attributes.
381
749
 
382
750
  ```ruby
383
- config.logger = Lumberjack::Logger.new(Lumberjack::SyslogDevice.new)
751
+ logger = Lumberjack::Logger.new($stderr, progname: "MyApp")
752
+ $stderr = logger
753
+
754
+ # These statements will now do the same thing
755
+ logger.unknown("Something went wrong")
756
+ $stderr.puts "Something went wrong"
757
+
758
+ # You can set the default level to set the level when using the I/O methods
759
+ logger.default_level = :warn
760
+ $stderr.puts "This is a warning message" # logged as a warning
384
761
  ```
385
762
 
763
+ ### Integrations
764
+
765
+ #### Rails
766
+
767
+ > [!WARNING]
768
+ > If you are using Rails, you must use the [lumberjack_rails](https://github.com/bdurand/lumberjack_rails) gem.
769
+ >
770
+ > Rails does its own monkey patching to the standard library Logger to support tagged logging, silencing logs, and broadcast logging.
771
+
772
+ #### Other Integrations
773
+
774
+ - [lumberjack_sidekiq](https://github.com/bdurand/lumberjack_sidekiq) - Integrates Lumberjack with Sidekiq for background job logging.
775
+ - [lumberjack_datadog](https://github.com/bdurand/lumberjack_datadog) - Integrates Lumberjack with Datadog by outputting logs in JSON using Datadog's standard attributes.
776
+ - [lumberjack_local_logger](https://github.com/bdurand/lumberjack_local_logger) - Lightweight wrapper around Lumberjack::Logger that allows contextual logging with custom levels, prognames, and attributes without affecting the parent logger.
777
+ - Check [RubyGems](https://rubygems.org/gems) for other integrations
778
+
386
779
  ## Installation
387
780
 
388
781
  Add this line to your application's Gemfile: