iugu_logger 0.10.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9f3b99e1a559a5f178c6b1912682683904d257c4f951f33ea5dce7f61e8c3e0d
4
+ data.tar.gz: 3eae5a9150343a4a467d422eb87956fe7995a0f83cd0636304559ba767fda055
5
+ SHA512:
6
+ metadata.gz: 4db9c2d097eb568762a8e931f7d484ca3b294d25a926f84b1031f75ef0bc6d27cf50c466a9d2049cccfe9221396d541608f73f65cade6af3d68f3efc2be56fe0
7
+ data.tar.gz: a1e4f13b8b04c6be87b5cacf2dbac6c09b1370906b2e83a7427eb3a63197a45033069085d148c78b5b582424b9441021ca22f1a71aedf09661ae0156e353903a
data/LICENSE.md ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 iugu
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,379 @@
1
+ # iugu_logger
2
+
3
+ > SDK Ruby do iugu Logging Standard (ILS) — schema canônico, PII detection, trace context, registry de eventos, paridade `rails_semantic_logger`. Funciona de Ruby 2.4 (platform) até 3.x (Rails 8).
4
+
5
+ SDK Ruby que implementa o **iugu Logging Standard (ILS)**: logging estruturado JSON, schema canônico de eventos, detecção de PII e correlação de trace context.
6
+
7
+ ---
8
+
9
+ ## Status: **v0.9.0 — em produção**
10
+
11
+ Validado em produção em 2026-05-13 com tráfego real. Componentes:
12
+
13
+ | Componente | Versão | Estado |
14
+ |---|---|---|
15
+ | `IuguLogger.configure` DSL + `Logger.event` core | 0.1 | ✅ |
16
+ | Custom `:note` severity (entre `:info` e `:warn`) | 0.1 | ✅ |
17
+ | `IuguLogger::Pii` — 3-layer scanner + BR regex + SAFE_PATTERNS | 0.2 | ✅ |
18
+ | `IuguLogger::Schema::Validator` — registry, `:off`/`:warn`/`:strict` + Levenshtein | 0.3 | ✅ |
19
+ | `IuguLogger::TraceContext` — OTEL/Datadog/W3C/X-Request-Id chain | 0.3.1 | ✅ |
20
+ | `IuguLogger::TenantContext` — Rack env extractor | 0.3.1 | ✅ |
21
+ | `IuguLogger::Buffer` (thread-local) + `RequestLogger` Rack middleware | 0.4.0 | ✅ |
22
+ | `IuguLogger::JobLogger` — Sidekiq + ActiveJob middlewares | 0.4.1 | ✅ |
23
+ | `IuguLogger::Railtie` — auto-config Rails + Sidekiq + ActionController runtime subscriber | 0.5 → 0.8.1 | ✅ |
24
+ | Install generator + smoke rake task | 0.6.0 | ✅ |
25
+ | PII timing fix (re-read tenant after `@app.call`) | 0.6.3 | ✅ |
26
+ | **Data-completeness-first PII defaults** (`:detect_only` para CPF/CNPJ/phone/email/address) | **0.7.0** | ✅ |
27
+ | **`RequestLogger` enrichment** (`params`, `format`, `status_message`, `rails.*`) | **0.8.0** | ✅ |
28
+ | **CC Luhn check + format/runtime fallbacks** | **0.8.1** | ✅ |
29
+ | **`max_log_size_kb` truncation + conformance runner** | **0.9.0** | ✅ |
30
+ | **Single-line JSON default em todo ambiente** (`IUGU_LOG_PRETTY` ativa pretty) | unreleased | ✅ |
31
+ | **Trace enrichment OTEL-aware** (`source`, `sampled`, `otel` diag, `parent_id` backfill) | unreleased | ✅ |
32
+ | **`service.instance` opt-in** (`emit_service_instance`, default off) | unreleased | ✅ |
33
+ | **Trace auto-correlation em `event()`** (herda do Buffer; fallback OTEL ambiente) | unreleased | ✅ |
34
+ | Conformance suite cross-language passing + v1.0 publish | 1.0 | ⏳ |
35
+
36
+ **~197 RSpec examples** passing em Ruby **2.4 / 2.7 / 3.2** matrix.
37
+
38
+ ---
39
+
40
+ ## Integração em 3 passos
41
+
42
+ ### 1. Adicionar a gem ao `Gemfile`
43
+
44
+ ```ruby
45
+ gem "iugu_logger", "~> 0.9"
46
+ ```
47
+
48
+ Depois rode `bundle install`. A gem é pública na RubyGems.org — sem `source` customizado, autenticação ou secret de build.
49
+
50
+ Defina `GIT_SHA` no build/deploy (`service.version` dos eventos): no Dockerfile via `ARG GIT_SHA` + `ENV GIT_SHA=${GIT_SHA}`, ou via env no Deployment.
51
+
52
+ ### 2. Gerar initializer + populate Rack tenant + smoke
53
+
54
+ ```sh
55
+ rails g iugu_logger:install
56
+ bundle exec rake iugu_logger:smoke
57
+ ```
58
+
59
+ Pra popular `iugu.account_id` nos eventos canônicos, adicionar no `ApplicationController` (ou `Api::BaseController`):
60
+
61
+ ```ruby
62
+ include Api::IuguTenantContext # popula request.env["iugu.current_account_id"] após :authenticate
63
+ ```
64
+
65
+ Exemplo do concern (que vive no app, não no SDK):
66
+
67
+ ```ruby
68
+ # app/controllers/concerns/api/iugu_tenant_context.rb
69
+ module Api
70
+ module IuguTenantContext
71
+ extend ActiveSupport::Concern
72
+ included do
73
+ before_action :populate_iugu_tenant_context
74
+ end
75
+
76
+ private
77
+
78
+ def populate_iugu_tenant_context
79
+ return if current_account.blank?
80
+ request.env["iugu.current_account_id"] = current_account.id
81
+ request.env["iugu.current_tier"] = current_account.tier if current_account.respond_to?(:tier)
82
+ rescue StandardError => e
83
+ Rails.logger.warn("IuguTenantContext: #{e.class}: #{e.message}")
84
+ end
85
+ end
86
+ end
87
+ ```
88
+
89
+ ---
90
+
91
+ ## O canonical event (`http.request.completed`) — exemplo real de prod
92
+
93
+ ```jsonc
94
+ {
95
+ "@timestamp": "2026-05-13T15:03:13.835646Z",
96
+ "log.level": "info",
97
+ "event.kind": "event",
98
+ "event.action": "http.request.completed",
99
+ "message": "PATCH /api/v1/payments 200 [39ms]",
100
+
101
+ "service": {
102
+ "name": "payments-api",
103
+ "version": "1db43d1c238229c550a68d44c3be6892fc11d398", // build SHA
104
+ "environment": "production"
105
+ // "instance" (= pod name) é opt-in: por padrão NÃO é emitido, pois o
106
+ // Alloy já anexa o label `pod_name`. Habilite com
107
+ // c.emit_service_instance = true em contextos sem coletor (dev/local).
108
+ },
109
+
110
+ "trace": {
111
+ "id": "6a0492b10000000027ed5c23af8b1ff0",
112
+ "span_id": "77c72a8787354d51",
113
+ "parent_id": null, // span do chamador upstream; null = trace nasceu aqui
114
+ "source": "opentelemetry", // opentelemetry | datadog | w3c | request_id
115
+ "sampled": true // decisão de sampling (quando a origem expõe)
116
+ },
117
+
118
+ "iugu": {
119
+ "account_id": "1Huj2DcSjtUnVPQbAGqwpR" // tenant
120
+ },
121
+
122
+ "request": {
123
+ "id": "3ba30263-0786-4fa7-ad3a-5a34a5012d69",
124
+ "method": "PATCH",
125
+ "path": "/api/v1/payments",
126
+ "source": "api",
127
+ "format": "json", // v0.8.0
128
+ "params": { /* payload completo, Rails filter_parameters aplicado */ } // v0.8.0
129
+ },
130
+
131
+ "rails": { // v0.8.0
132
+ "controller": "Api::V1::PaymentsController",
133
+ "action": "update",
134
+ "view_runtime_ms": 0.21, // v0.8.1 (via process_action subscriber)
135
+ "db_runtime_ms": 4.50 // v0.8.1
136
+ },
137
+
138
+ "http": {
139
+ "status_code": 200,
140
+ "status_message": "OK", // v0.8.0
141
+ "duration_ms": 39
142
+ },
143
+
144
+ "pii": {
145
+ "scanned": true,
146
+ "detected": ["cnpj", "phone", "email"], // detection-only por default
147
+ "redacted": 0 // só CC + credenciais redactam
148
+ }
149
+ }
150
+ ```
151
+
152
+ **Paridade com `rails_semantic_logger` legacy** (Completed #...) + valor adicionado iugu (`event.action`, `service.version`, `service.instance`, `iugu.account_id`, `pii.detected`, `trace.id` correlation).
153
+
154
+ ---
155
+
156
+ ## API
157
+
158
+ ### Emissão direta de evento
159
+
160
+ ```ruby
161
+ IuguLogger.event("fraud.feedzai.payment.created",
162
+ message: "feedzai payment payload sent",
163
+ iugu: { account_id: account.id, tier: account.tier },
164
+ fraud: { feedzai_environment: "prod", lifecycle_id: "PIXUGU:..." })
165
+ ```
166
+
167
+ **Trace auto-correlation:** eventos emitidos durante um request/job herdam
168
+ automaticamente o `trace.*` (mesmo `trace_id` do `http.request.completed` /
169
+ log consolidado), sem você passar nada. A resolução é Buffer (preenchido pelo
170
+ RequestLogger) → span ambiente do OpenTelemetry/Datadog (cobre jobs/scripts).
171
+ Passar `trace:` explicitamente sobrescreve. Fora de qualquer contexto de
172
+ trace, o bloco é omitido.
173
+
174
+ ### Severity (incluindo `:note` custom)
175
+
176
+ ```ruby
177
+ IuguLogger.event("pix.out.timeout",
178
+ severity: :error,
179
+ message: "JDPI timeout after 30s",
180
+ pix: { end_to_end_id: e2e })
181
+ ```
182
+
183
+ Levels: `:trace`, `:debug`, `:info`, `:note` (custom — entre info e warn), `:warn`, `:error`, `:fatal`.
184
+
185
+ ### Buffer thread-local (in-app logs durante request)
186
+
187
+ ```ruby
188
+ IuguLogger::Buffer.current.push(severity: :info, message: "validating pix request")
189
+ IuguLogger::Buffer.current.push(severity: :note, message: "pix accepted by jdpi")
190
+ ```
191
+
192
+ `RequestLogger` drena no fim da request → `logs: [...]` no evento `http.request.completed`. **1 log/request consolidado**.
193
+
194
+ ### ActiveJob
195
+
196
+ ```ruby
197
+ class ApplicationJob < ActiveJob::Base
198
+ include IuguLogger::JobLogger::ActiveJob
199
+ end
200
+ ```
201
+
202
+ Cada execução de job emite `activejob.job.completed` (ou `.failed`) com `request: { id: job_id, source: "activejob" }`, `labels: { job_class, queue, attempt }`, `duration_ms`, `logs: [...]`.
203
+
204
+ ### Sidekiq
205
+
206
+ Auto-registrado pelo Railtie quando Sidekiq é detectado no boot. Standalone:
207
+
208
+ ```ruby
209
+ Sidekiq.configure_server do |config|
210
+ config.server_middleware { |chain| chain.add IuguLogger::JobLogger::Sidekiq }
211
+ end
212
+ ```
213
+
214
+ ---
215
+
216
+ ## Configuração
217
+
218
+ ### Override via `IuguLogger.configure`
219
+
220
+ ```ruby
221
+ IuguLogger.configure do |c|
222
+ c.service_name = "payments-api" # auto-derived em Rails
223
+ c.service_version = ENV["GIT_SHA"] || "0.0.0"
224
+ c.service_environment = Rails.env
225
+
226
+ c.format = %w[1 true yes].include?(ENV["IUGU_LOG_PRETTY"].to_s.downcase) ? :pretty : :json
227
+ # ↑ single-line JSON em todo ambiente por padrão; IUGU_LOG_PRETTY=true ativa pretty local
228
+
229
+ c.event_action_validator = :warn # :off | :warn | :strict
230
+ c.event_action_registry = JSON.parse(File.read("dist/registry.json"))
231
+
232
+ # service.instance (= HOSTNAME/POD_NAME) — OFF por padrão. Em K8s + Alloy o
233
+ # label `pod_name` já cobre isso; habilite só em dev/local ou fora do K8s.
234
+ # c.emit_service_instance = true
235
+ end
236
+ ```
237
+
238
+ ### Schema validator
239
+
240
+ | Mode | Comportamento |
241
+ |---|---|
242
+ | `:off` (default sem registry) | Sem validation, aceita qualquer `event.action` |
243
+ | `:warn` | Anota `labels.schema_warning: "unknown_event_action"`, emite normal |
244
+ | `:strict` | Raise `IuguLogger::UnknownEventAction` (sugestões typo via Levenshtein) ou `SchemaViolation` (campos required ausentes) |
245
+
246
+ ### PII strategies — data-completeness-first (v0.7+)
247
+
248
+ | Tipo | Default | Comportamento |
249
+ |---|---|---|
250
+ | `cpf`, `cnpj`, `phone`, `email`, `address` | `:detect_only` | Conteúdo preservado, `pii.detected` populado |
251
+ | `cc` (cartão) — **com validação Luhn** (v0.8.1) | `:last4` | `**** **** **** 1234` (PCI-DSS) |
252
+ | `aws_key`, `bearer`, `url_with_creds` | `:full_redact` | `[AWS_KEY_REDACTED]` (credenciais — nunca user data) |
253
+
254
+ **`account_id` 32-hex** (ILS-002) e **schema canonical paths** (`trace.*`, `request.id`, `service.*`) — `SAFE_KEY_PATHS` skipa scan inteiramente.
255
+
256
+ **Override per-app** (apps que precisam stricter, ex: external log export):
257
+
258
+ ```ruby
259
+ c.pii_redaction = IuguLogger::Pii::DEFAULT_STRATEGIES.merge(
260
+ cpf: :full_redact,
261
+ email: :full_redact
262
+ )
263
+ ```
264
+
265
+ ### Trace context (chain de fallback)
266
+
267
+ `IuguLogger::TraceContext.extract(rack_env: env)` resolve a origem nesta ordem (primeira não-nil vence):
268
+
269
+ 1. `OpenTelemetry::Trace.current_span` (Ruby ≥ 2.6 com otel-api) → `source: "opentelemetry"`
270
+ 2. `Datadog::Tracing.active_trace` (ddtrace) → `source: "datadog"`
271
+ 3. W3C `traceparent` header → `source: "w3c"`
272
+ 4. iugu legacy `X-Request-Id` / Rails `action_dispatch.request_id` → `source: "request_id"` (correlação só, `span_id` zerado)
273
+ 5. `nil` — Logger emite sem o bloco `trace.*`
274
+
275
+ O bloco `trace` resultante carrega:
276
+
277
+ | Campo | Descrição |
278
+ |---|---|
279
+ | `id` | trace ID 32-hex — vem direto do OTEL quando ativo (o nome ECS já carrega o identificador OpenTelemetry) |
280
+ | `span_id` | span ID 16-hex do span local |
281
+ | `parent_id` | span do chamador upstream, backfilled do `traceparent` recebido quando o trace foi continuado. **Presente = trace veio de outro serviço; `null` = trace nasceu nesta chamada** |
282
+ | `source` | origem do contexto: `opentelemetry` / `datadog` / `w3c` / `request_id` |
283
+ | `sampled` | decisão de sampling (bit das trace-flags), quando a origem expõe. `false` = trace não será exportado ao backend, mas o log ainda correlaciona pelo `id` |
284
+ | `otel` | diagnóstico `"not_configured"` quando o SDK do OpenTelemetry está no bundle mas nunca foi inicializado (`OpenTelemetry::SDK.configure` não rodou). Ausente quando OTEL está ativo ou não está no bundle |
285
+
286
+ ---
287
+
288
+ ## Migração `Rails.logger.X` → `IuguLogger.event`
289
+
290
+ ### Regra de coexistência (spec §10)
291
+
292
+ **Não remover `Rails.logger.X` antes da gem v0.8+ estar validada em produção e o evento canônico carregar todos os dados.** Pattern de migração rolling:
293
+
294
+ ```ruby
295
+ def submit_payment(params:)
296
+ enriched = enrich(params)
297
+
298
+ # Legacy — mantido durante rolling, ops/suporte/fraude dependem
299
+ Rails.logger.info("Payload enviado para a feedzai", enriched)
300
+
301
+ # Canônico — schema iugu, eventualmente substitui o legacy
302
+ IuguLogger.event("fraud.feedzai.payment.created",
303
+ message: "Payload enviado para a feedzai",
304
+ fraud: { feedzai_environment:, payload: enriched })
305
+
306
+ post_payment(enriched)
307
+ end
308
+ ```
309
+
310
+ Após validação em prod (~dias), follow-up PR remove a linha legacy.
311
+
312
+ ### Exemplos antes/depois
313
+
314
+ **Antes (string interpolation — antipattern):**
315
+
316
+ ```ruby
317
+ Rails.logger.error("Erro processando #{user.id}: #{e.message}")
318
+ ```
319
+
320
+ **Depois (kv-args + schema):**
321
+
322
+ ```ruby
323
+ IuguLogger.event("user.processing.failed",
324
+ severity: :error,
325
+ iugu: { user_id: user.id },
326
+ error: { type: e.class.name, message: e.message })
327
+ ```
328
+
329
+ ---
330
+
331
+ ## Decisões aplicadas
332
+
333
+ | ID | Decisão | Implementação |
334
+ |---|---|---|
335
+ | ILS-002 | `iugu.account_id` 32-hex preservado | `Pii::SAFE_PATTERNS` + `SAFE_KEY_PATHS` |
336
+ | ILS-003 | Email `:detect_only` (deferido — agora **generalizado** em v0.7) | `Pii::DEFAULT_STRATEGIES` |
337
+ | §13.7 | Ruby 2.4 first-class | `gemspec.required_ruby_version >= 2.4` + CI matrix |
338
+ | **v0.7** | **Data-completeness-first** — PII detection-only por default | `Pii::DEFAULT_STRATEGIES` |
339
+ | **v0.8.0** | **`RequestLogger` enrichment** pra paridade com `rails_semantic_logger` | `request_logger.rb` |
340
+ | **v0.8.1** | **CC Luhn check** previne CNPJ false-positive | `Pii::Scanner#luhn_valid?` |
341
+ | **v0.9.0** | **`max_log_size_kb` truncation + conformance runner** | `Configuration#max_log_size_kb` + `spec/conformance/` |
342
+ | **unreleased** | **Single-line JSON default** em todo ambiente (Loki/Alloy: 1 evento/linha; pretty via `IUGU_LOG_PRETTY`) | `Configuration#format` |
343
+ | **unreleased** | **Trace context OTEL-aware** — `source`/`sampled`/`otel` diag + `parent_id` backfill do `traceparent` recebido | `trace_context.rb` |
344
+ | **unreleased** | **`service.instance` opt-in** — evita duplicar o label `pod_name` que o Alloy já anexa | `Configuration#emit_service_instance` |
345
+ | **unreleased** | **Trace auto-correlation** — `IuguLogger.event` herda o `trace.*` do request/job (Buffer > OTEL ambiente); `trace:` explícito vence | `Logger#inject_trace_context` |
346
+
347
+ ---
348
+
349
+ ## Distribuição
350
+
351
+ Publicada na [RubyGems.org](https://rubygems.org/gems/iugu_logger) — `gem "iugu_logger"`, sem autenticação. Versionamento segue [SemVer](https://semver.org) e o `CHANGELOG.md` acompanha cada release.
352
+
353
+ ---
354
+
355
+ ## Desenvolvimento
356
+
357
+ ```sh
358
+ bundle install
359
+ bundle exec rspec
360
+ ```
361
+
362
+ CI valida matriz Ruby 2.4 + 2.7 + 3.2 em todo PR.
363
+
364
+ ---
365
+
366
+ ## Compatibilidade
367
+
368
+ - Ruby >= 2.4 (cobre platform Rails 4.2 até modernos)
369
+ - Rails opcional (Railtie auto-config quando detectado)
370
+ - ActionController::API e ActionController::Base (subscriber pra `process_action.action_controller` v0.8.1)
371
+ - Sidekiq opcional (auto-registra)
372
+ - ActiveJob opcional (mixin opt-in)
373
+ - OpenTelemetry opcional (chain fallback)
374
+
375
+ ---
376
+
377
+ ## Ownership
378
+
379
+ Mantido pela Engenharia de Plataforma da iugu — `eng-plataforma@iugu.com`.
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+
5
+ module IuguLogger
6
+ module Generators
7
+ # Run via:
8
+ # rails g iugu_logger:install
9
+ #
10
+ # Creates `config/initializers/iugu_logger.rb` with sensible defaults.
11
+ # Idempotent — re-running asks before overwriting.
12
+ class InstallGenerator < ::Rails::Generators::Base
13
+ source_root File.expand_path('templates', __dir__)
14
+
15
+ desc 'Generate config/initializers/iugu_logger.rb with iugu Logging Standard defaults'
16
+
17
+ def create_initializer
18
+ template 'iugu_logger.rb.tt', 'config/initializers/iugu_logger.rb'
19
+ end
20
+
21
+ def post_install_summary
22
+ say "\n iugu_logger #{IuguLogger::VERSION} initializer installed.", :green
23
+ say ' Run `bundle exec rake iugu_logger:smoke` to validate the setup.', :green
24
+ end
25
+
26
+ private
27
+
28
+ # Best-effort default service name from the Rails app class.
29
+ # Same heuristic as IuguLogger::Railtie#derive_service_name (kept in sync).
30
+ def default_service_name
31
+ klass = Rails.application.class.name.to_s
32
+ return 'rails-app' if klass.empty?
33
+
34
+ first = klass.split('::').first
35
+ first.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
36
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
37
+ .downcase
38
+ .tr('_', '-')
39
+ rescue StandardError
40
+ 'rails-app'
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # iugu Logging Standard (ILS) — Ruby SDK setup.
4
+ #
5
+ # Generated by `rails g iugu_logger:install`. Edit freely; sensible defaults
6
+ # below cover the canonical case. After changes, validate with:
7
+ #
8
+ # bundle exec rake iugu_logger:smoke
9
+
10
+ IuguLogger.configure do |c|
11
+ c.service_name = '<%= default_service_name %>'
12
+ # service_version: short git SHA from build/deploy time. Set GIT_SHA at
13
+ # build/deploy (Dockerfile ARG/ENV or K8s downward API).
14
+ c.service_version = ENV['GIT_SHA'] || '0.0.0'
15
+ c.service_environment = Rails.env
16
+
17
+ # service.instance (= HOSTNAME/POD_NAME) is OFF by default: in the K8s +
18
+ # Alloy pipeline the `pod_name` label already carries it, so emitting it
19
+ # here would duplicate it on every line. Enable for local/non-K8s contexts
20
+ # where no collector enriches the log:
21
+ # c.emit_service_instance = true
22
+
23
+ # Single-line JSON by default in EVERY environment (Loki/Alloy ingestion
24
+ # expects exactly one event per line). Opt into multi-line pretty output
25
+ # locally for legibility with IUGU_LOG_PRETTY=true.
26
+ c.format = %w[1 true yes].include?(ENV['IUGU_LOG_PRETTY'].to_s.downcase) ? :pretty : :json
27
+
28
+ # event.action validator:
29
+ # :off — no validation (default if no registry loaded)
30
+ # :warn — annotates labels.schema_warning, never blocks emit
31
+ # :strict — raises UnknownEventAction / SchemaViolation
32
+ # Move to :strict once `event_action_registry` is loaded and event coverage
33
+ # is complete.
34
+ c.event_action_validator = :warn
35
+
36
+ # PII strategies (since v0.7 — data-completeness-first):
37
+ # - cpf/cnpj/phone/email/address → :detect_only
38
+ # PII is DETECTED (audit-queryable via `pii.detected`) but not
39
+ # removed from the log. Ops, support, fraud, and ML pipelines
40
+ # depend on the raw values.
41
+ # - cc → :last4 (PCI-DSS hard rule)
42
+ # - aws_key/bearer/url_with_creds → :full_redact (credentials)
43
+ # iugu.account_id 32-hex is preserved unconditionally (ILS-002 SAFE_PATTERN).
44
+ #
45
+ # For apps that need stricter redaction (e.g. external log export
46
+ # targets), override per-type:
47
+ #
48
+ # c.pii_redaction = IuguLogger::Pii::DEFAULT_STRATEGIES.merge(
49
+ # cpf: :full_redact,
50
+ # email: :full_redact
51
+ # )
52
+ end