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.
- checksums.yaml +4 -4
- data/ARCHITECTURE.md +524 -176
- data/CHANGELOG.md +89 -0
- data/README.md +604 -211
- data/UPGRADE_GUIDE.md +80 -0
- data/VERSION +1 -1
- data/lib/lumberjack/attribute_formatter.rb +451 -0
- data/lib/lumberjack/attributes_helper.rb +100 -0
- data/lib/lumberjack/context.rb +120 -23
- data/lib/lumberjack/context_logger.rb +620 -0
- data/lib/lumberjack/device/buffer.rb +209 -0
- data/lib/lumberjack/device/date_rolling_log_file.rb +10 -62
- data/lib/lumberjack/device/log_file.rb +76 -29
- data/lib/lumberjack/device/logger_wrapper.rb +137 -0
- data/lib/lumberjack/device/multi.rb +92 -30
- data/lib/lumberjack/device/null.rb +26 -8
- data/lib/lumberjack/device/size_rolling_log_file.rb +13 -54
- data/lib/lumberjack/device/test.rb +337 -0
- data/lib/lumberjack/device/writer.rb +184 -176
- data/lib/lumberjack/device.rb +134 -15
- data/lib/lumberjack/device_registry.rb +90 -0
- data/lib/lumberjack/entry_formatter.rb +357 -0
- data/lib/lumberjack/fiber_locals.rb +55 -0
- data/lib/lumberjack/forked_logger.rb +143 -0
- data/lib/lumberjack/formatter/date_time_formatter.rb +14 -3
- data/lib/lumberjack/formatter/exception_formatter.rb +12 -2
- data/lib/lumberjack/formatter/id_formatter.rb +13 -1
- data/lib/lumberjack/formatter/inspect_formatter.rb +14 -1
- data/lib/lumberjack/formatter/multiply_formatter.rb +10 -0
- data/lib/lumberjack/formatter/object_formatter.rb +13 -1
- data/lib/lumberjack/formatter/pretty_print_formatter.rb +15 -2
- data/lib/lumberjack/formatter/redact_formatter.rb +18 -3
- data/lib/lumberjack/formatter/round_formatter.rb +12 -0
- data/lib/lumberjack/formatter/string_formatter.rb +9 -1
- data/lib/lumberjack/formatter/strip_formatter.rb +13 -1
- data/lib/lumberjack/formatter/structured_formatter.rb +18 -2
- data/lib/lumberjack/formatter/tagged_message.rb +10 -32
- data/lib/lumberjack/formatter/tags_formatter.rb +32 -0
- data/lib/lumberjack/formatter/truncate_formatter.rb +8 -1
- data/lib/lumberjack/formatter.rb +271 -141
- data/lib/lumberjack/formatter_registry.rb +84 -0
- data/lib/lumberjack/io_compatibility.rb +133 -0
- data/lib/lumberjack/local_log_template.rb +209 -0
- data/lib/lumberjack/log_entry.rb +154 -79
- data/lib/lumberjack/log_entry_matcher/score.rb +276 -0
- data/lib/lumberjack/log_entry_matcher.rb +126 -0
- data/lib/lumberjack/logger.rb +328 -556
- data/lib/lumberjack/message_attributes.rb +38 -0
- data/lib/lumberjack/rack/context.rb +66 -15
- data/lib/lumberjack/rack.rb +0 -2
- data/lib/lumberjack/remap_attribute.rb +24 -0
- data/lib/lumberjack/severity.rb +52 -15
- data/lib/lumberjack/tag_context.rb +8 -71
- data/lib/lumberjack/tag_formatter.rb +22 -188
- data/lib/lumberjack/tags.rb +15 -21
- data/lib/lumberjack/template.rb +252 -62
- data/lib/lumberjack/template_registry.rb +60 -0
- data/lib/lumberjack/utils.rb +198 -48
- data/lib/lumberjack.rb +167 -59
- data/lumberjack.gemspec +4 -2
- metadata +41 -15
- data/lib/lumberjack/device/rolling_log_file.rb +0 -145
- data/lib/lumberjack/rack/request_id.rb +0 -31
- data/lib/lumberjack/rack/unit_of_work.rb +0 -21
- data/lib/lumberjack/tagged_logger_support.rb +0 -81
- data/lib/lumberjack/tagged_logging.rb +0 -29
data/README.md
CHANGED
@@ -4,385 +4,778 @@
|
|
4
4
|
[](https://github.com/testdouble/standard)
|
5
5
|
[](https://badge.fury.io/rb/lumberjack)
|
6
6
|
|
7
|
-
Lumberjack is
|
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
|
-
|
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
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
79
|
+
##### Nested Context Blocks
|
31
80
|
|
32
|
-
|
81
|
+
Context blocks can be nested, with inner contexts inheriting and potentially overriding outer context settings:
|
33
82
|
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
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
|
-
|
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
|
-
|
93
|
+
logger.info("API request completed") # Back to: user_id: 123, service: "api"
|
94
|
+
end
|
95
|
+
```
|
96
|
+
|
97
|
+
#### Forking Loggers
|
43
98
|
|
44
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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.
|
60
|
-
logger.
|
61
|
-
logger.
|
62
|
-
logger.
|
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
|
-
|
154
|
+
|
155
|
+
logger.info("Outside of context") # Does not include user_id or session
|
65
156
|
```
|
66
157
|
|
67
|
-
|
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
|
-
|
71
|
-
|
72
|
-
logger.
|
73
|
-
logger.
|
74
|
-
logger.info("
|
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
|
-
|
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.
|
176
|
+
logger.context do
|
177
|
+
logger.tag(request_id: "req-123") do
|
178
|
+
logger.info("Processing request") # Includes request_id
|
83
179
|
|
84
|
-
|
85
|
-
|
86
|
-
|
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("
|
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
|
-
|
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
|
-
|
95
|
-
|
96
|
-
|
97
|
-
|
98
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
209
|
+
There is also a global `Lumberjack` context that applies to all Lumberjack loggers.
|
107
210
|
|
108
211
|
```ruby
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
227
|
+
headers: { "Content-Type" => "application/json" }
|
136
228
|
},
|
137
229
|
response: {
|
138
230
|
status: 201,
|
139
|
-
duration_ms:
|
231
|
+
duration_ms: 45.2,
|
232
|
+
size_bytes: 1024
|
140
233
|
},
|
141
234
|
user: {
|
142
|
-
id:
|
143
|
-
role:
|
235
|
+
id: 123,
|
236
|
+
role: "admin",
|
237
|
+
permissions: ["read", "write", "delete"]
|
144
238
|
}
|
145
|
-
|
239
|
+
)
|
146
240
|
```
|
147
241
|
|
148
|
-
|
242
|
+
#### Attribute Inheritance and Merging
|
149
243
|
|
150
|
-
|
244
|
+
Attributes from different sources are merged together, with more specific attributes taking precedence:
|
151
245
|
|
152
|
-
|
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.
|
156
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
340
|
+
You can also format attributes based on the attribute name:
|
167
341
|
|
168
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
382
|
+
Lumberjack provides several predefined formatters that can be referenced by symbol:
|
192
383
|
|
193
384
|
```ruby
|
194
|
-
|
195
|
-
|
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
|
-
|
198
|
-
|
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
|
-
|
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
|
-
|
205
|
-
|
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
|
-
|
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
|
-
|
436
|
+
```ruby
|
437
|
+
class User
|
438
|
+
attr_accessor :id, :name
|
220
439
|
|
221
|
-
|
440
|
+
def to_log_format
|
441
|
+
"User[id: #{ id }, name: #{ name }]"
|
442
|
+
end
|
443
|
+
end
|
444
|
+
```
|
222
445
|
|
223
|
-
|
446
|
+
Primitive classes (`String`, `Integer`, `Float`, `TrueClass`, `FalseClass`, `NilClass`, `BigDecimal`) will not use `to_log_format`.
|
224
447
|
|
225
|
-
|
448
|
+
#### Building An Entry Formatter
|
226
449
|
|
227
|
-
|
450
|
+
The Entry Formatter coordinates both message and attribute formatting, providing a unified configuration interface:
|
228
451
|
|
229
|
-
|
452
|
+
##### Complete Entry Formatter Setup
|
230
453
|
|
231
454
|
```ruby
|
232
|
-
|
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
|
-
|
473
|
+
#### Merging Formatters
|
236
474
|
|
237
|
-
|
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
|
-
|
241
|
-
|
242
|
-
|
243
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
497
|
+
##### Writer Device
|
254
498
|
|
255
|
-
The
|
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
|
-
|
259
|
-
|
260
|
-
|
261
|
-
|
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
|
-
|
264
|
-
|
265
|
-
logger
|
509
|
+
```ruby
|
510
|
+
# Daily log rotation
|
511
|
+
logger = Lumberjack::Logger.new("/var/log/app.log", 'daily')
|
512
|
+
```
|
266
513
|
|
267
|
-
|
268
|
-
logger.tag_formatter.add(Numeric, &:round)
|
514
|
+
##### Multi Device
|
269
515
|
|
270
|
-
|
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
|
-
|
273
|
-
|
274
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
285
|
-
|
545
|
+
logger = Lumberjack::Logger.new(:test)
|
546
|
+
```
|
547
|
+
|
548
|
+
> [!TIP]
|
549
|
+
> See the [testing utilities](#testing-utilities) section for more information.
|
286
550
|
|
287
|
-
|
288
|
-
Lumberjack::Logger.new("application.log", :template => ":time - :message")
|
551
|
+
##### Null Device
|
289
552
|
|
290
|
-
|
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
|
-
|
295
|
-
|
296
|
-
Lumberjack::Logger.new("application.log", :template => template)
|
555
|
+
```ruby
|
556
|
+
logger = Lumberjack::Logger.new(:null)
|
297
557
|
```
|
298
558
|
|
299
|
-
|
559
|
+
#### Custom Devices
|
300
560
|
|
301
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
309
|
-
logger = Lumberjack::Logger.new("application.log", :buffer_size => 8192)
|
601
|
+
Lumberjack::Device.register(:my_device, MyDevice)
|
310
602
|
|
311
|
-
#
|
312
|
-
|
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
|
-
|
608
|
+
#### Templates
|
316
609
|
|
317
|
-
The
|
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
|
-
|
612
|
+
##### Basic Template Usage
|
320
613
|
|
321
|
-
|
614
|
+
```ruby
|
615
|
+
# Simple template with common fields
|
616
|
+
logger = Lumberjack::Logger.new(STDOUT, template: "{{time}} {{severity}} {{message}}")
|
322
617
|
|
323
|
-
|
618
|
+
logger.info("Application started")
|
619
|
+
# Output: 2025-09-03T14:30:15.123456 INFO Application started
|
620
|
+
```
|
324
621
|
|
325
|
-
|
622
|
+
##### Available Template Variables
|
326
623
|
|
327
|
-
|
624
|
+
Templates support the following placeholder variables:
|
328
625
|
|
329
|
-
|
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
|
-
|
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
|
-
|
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
|
645
|
+
The severity can also have an optional formatting argument added to it.
|
336
646
|
|
337
|
-
|
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
|
-
|
655
|
+
##### Template Options
|
340
656
|
|
341
|
-
|
657
|
+
You can customize how template variables are formatted using template options:
|
342
658
|
|
343
659
|
```ruby
|
344
|
-
|
345
|
-
|
346
|
-
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
|
351
|
-
|
352
|
-
|
353
|
-
|
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
|
-
|
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
|
-
|
681
|
+
logger = Lumberjack::Logger.new(STDOUT, template: :local, exclude_attributes: ["host", "env", "version"])
|
360
682
|
```
|
361
683
|
|
362
|
-
|
684
|
+
### Testing Utilities
|
685
|
+
|
686
|
+
The `Test` device captures log entries in memory for testing and assertions:
|
363
687
|
|
364
688
|
```ruby
|
365
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
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
|
-
|
743
|
+
Lumberjack.raise_logging_errors = true
|
378
744
|
```
|
379
745
|
|
380
|
-
|
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
|
-
|
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:
|