File: examples.html.md

package info (click to toggle)
ruby-dry-logger 1.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 444 kB
  • sloc: ruby: 2,170; makefile: 4; sh: 4
file content (337 lines) | stat: -rw-r--r-- 6,886 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
---
title: Examples
layout: gem-single
name: dry-logger
---

This page shows complete, realistic configurations for common use cases, combining multiple dry-logger features.

## Development setup

Maximum readability with colorized output:

```ruby
require "dry/logger"

# Register a custom colorized template
Dry::Logger.register_template(
  :dev,
  "<gray>%<time>s</gray> <cyan>[%<progname>s]</cyan> " \
  "<yellow>%<severity>s</yellow> %<message>s <blue>%<payload>s</blue>"
)

logger = Dry.Logger(:my_app,
  template: :dev,
  level: :debug
)

logger.info("Server ready", port: 3000, env: "development")
# (colorized output) 2023-10-15 14:40:00 [my_app] INFO Server ready port=3000 env="development"
```

## Production setup

Structured JSON logging with error file and filters:

```ruby
require "dry/logger"

PRODUCTION_FILTERS = [
  :password,
  :api_key,
  :secret_token,
  :access_token,
  :ssn,
  :credit_card_number
].freeze

logger = Dry.Logger(:my_app) do |setup|
  # Main JSON log file
  setup.add_backend(
    stream: "logs/production.json",
    formatter: :json,
    filters: PRODUCTION_FILTERS
  )

  # Separate error file
  setup.add_backend(
    stream: "logs/errors.json",
    formatter: :json,
    filters: PRODUCTION_FILTERS,
    log_if: :error?
  )
end

logger.info("Request processed",
  user_id: 123,
  action: "update_profile",
  duration_ms: 45,
  password: "secret"  # Filtered
)
# {"progname":"my_app","severity":"INFO","time":"2023-10-15T14:42:30Z","message":"Request processed","user_id":123,"action":"update_profile","duration_ms":45,"password":"[FILTERED]"}
```

## Web applications

### Rack/Rails application

Combine different formatters and filters for different log types:

```ruby
require "dry/logger"

# Define filters for sensitive data
FILTER_PARAMS = [
  :password,
  :password_confirmation,
  :api_key,
  :secret_token,
  :access_token,
  :ssn,
  :credit_card_number
].freeze

logger = Dry.Logger(:rails_app) do |setup|
  # General application logs (string format)
  setup.add_backend(
    stream: "logs/application.log",
    formatter: :string,
    template: :details,
    filters: FILTER_PARAMS
  )

  # HTTP request logs (rack format)
  setup.add_backend(
    stream: "logs/requests.log",
    formatter: :rack,
    filters: FILTER_PARAMS,
    log_if: -> (entry) { entry.key?(:verb) && entry.key?(:path) }
  )

  # Error tracking in JSON
  setup.add_backend(
    stream: "logs/errors.json",
    formatter: :json,
    filters: FILTER_PARAMS,
    log_if: -> (entry) { entry.error? || entry.fatal? }
  )
end

# Application log
logger.info("User authenticated", user_id: 42)

# HTTP request log
logger.info(
  verb: "POST",
  path: "/api/users",
  status: 201,
  elapsed: "23ms",
  ip: "192.168.1.1",
  length: 512,
  params: {name: "John"}
)

# Error log
begin
  raise "Database timeout"
rescue => e
  logger.error(e)
end

# Use in Rails
Rails.logger = logger
```

## API applications

API-specific logging with custom templates and comprehensive filtering:

```ruby
require "dry/logger"

# API-specific filters
API_FILTERS = [
  # Auth headers
  :authorization,
  :api_key,
  "headers.authorization",
  "headers.x-api-key",

  # Request data
  :password,
  :secret,
  :token,

  # Response data
  "response.access_token",
  "response.refresh_token"
].freeze

# Custom template for API requests
Dry::Logger.register_template(
  :api,
  "%<time>s | %<verb>s %<path>s | Status: %<status>s | %<elapsed>s"
)

logger = Dry.Logger(:api) do |setup|
  # Console output for development
  setup.add_backend(
    stream: $stdout,
    formatter: :string,
    template: :api,
    filters: API_FILTERS
  )

  # JSON logs for aggregation
  setup.add_backend(
    stream: "logs/api.json",
    formatter: :json,
    filters: API_FILTERS
  )
end

logger.info(
  verb: "POST",
  path: "/api/orders",
  status: 201,
  elapsed: "120ms",
  authorization: "Bearer secret"  # Filtered
)
# Console: 2023-10-15 14:50:00 +0000 | POST /api/orders | Status: 201 | 120ms
# JSON: {"progname":"api",...,"authorization":"[FILTERED]"}
```

## Payment processing

PCI-compliant logging with comprehensive filters:

```ruby
require "dry/logger"

# PCI compliance filters
PAYMENT_FILTERS = [
  # Card data (PCI DSS requirement)
  :card_number,
  :cvv,
  :cvc,
  :expiry,
  :card_holder,
  "payment.card_number",
  "payment.cvv",

  # Billing data
  :billing_address,
  :account_number,
  :routing_number,

  # Customer PII
  :ssn,
  :tax_id,
  :email,
  :phone
].freeze

logger = Dry.Logger(:payment_processor,
  stream: "logs/payments.log",
  formatter: :json,
  filters: PAYMENT_FILTERS
)

logger.info("Payment processed",
  transaction_id: "txn_123",
  amount: 99.99,
  card_number: "4111111111111111",  # Will be filtered
  cvv: "123",                        # Will be filtered
  status: "success"
)
# {"transaction_id":"txn_123","amount":99.99,"card_number":"[FILTERED]","cvv":"[FILTERED]","status":"success"}
```

## Hybrid setup

Different backends for different purposes:

```ruby
require "dry/logger"

logger = Dry.Logger(:my_app) do |setup|
  # Colorized console for development
  setup.add_backend(
    stream: $stdout,
    formatter: :string,
    template: "<yellow>%<severity>s</yellow> %<message>s <blue>%<payload>s</blue>",
    log_if: -> (entry) { ENV["RACK_ENV"] == "development" }
  )

  # Detailed file logs
  setup.add_backend(
    stream: "logs/app.log",
    formatter: :string,
    template: :details
  )

  # JSON for analysis tools
  setup.add_backend(
    stream: "logs/app.json",
    formatter: :json
  )

  # Separate error file
  setup.add_backend(
    stream: "logs/errors.log",
    formatter: :string,
    template: :details,
    log_if: :error?
  )
end

logger.info("Application started", version: "1.2.3")
# Console: INFO Application started version="1.2.3" (colorized, development only)
# File: [my_app] [INFO] [2023-10-15 14:55:00 +0000] Application started version="1.2.3"
# JSON: {"progname":"my_app","severity":"INFO",...}
```

## Multi-environment configuration

Configure logger based on environment:

```ruby
require "dry/logger"

def setup_logger(env)
  case env
  when "development"
    Dry.Logger(:my_app,
      template: :dev,
      colorize: true,
      level: :debug
    )
  when "production"
    Dry.Logger(:my_app) do |setup|
      setup.add_backend(
        stream: "logs/production.json",
        formatter: :json,
        filters: production_filters
      )
      setup.add_backend(
        stream: "logs/errors.json",
        formatter: :json,
        filters: production_filters,
        log_if: :error?
      )
    end
  when "test"
    require "stringio"
    Dry.Logger(:my_app,
      stream: StringIO.new,
      level: :warn  # Suppress noise in tests
    )
  end
end

def production_filters
  [:password, :api_key, :secret_token, :ssn, :credit_card_number]
end

logger = setup_logger(ENV.fetch("RACK_ENV", "development"))
```