Skip to content

docs(core): instrumentation guide for lib-observability v2#38

Merged
gauchito91 merged 6 commits into
developfrom
docs/lib-o11y-usage-guide
Jul 23, 2026
Merged

docs(core): instrumentation guide for lib-observability v2#38
gauchito91 merged 6 commits into
developfrom
docs/lib-o11y-usage-guide

Conversation

@gauchito91

Copy link
Copy Markdown
Contributor

Adiciona docs/USAGE.md — guia prescritivo de como instrumentar um serviço com a lib-observability v2 (as features do #36).

Escrito para ser entregue a uma IA/engenheiro executar a instrumentação por serviço (Fase 3 do plano).

Conteúdo

  • Bootstrap (NewTelemetry) + a pegadinha do ApplyGlobals (bug nº1 de "não emite nada").
  • HTTP (Fiber v3 — com aviso de que apps Fiber v2 pulam).
  • gRPC (grpcmiddleware, sem Fiber).
  • SQL (sqlobs): caso simples, dbresolver (instrumentar cada *sql.DB antes do resolver), e o caveat do pool separado.
  • Cache (redisobs — Redis + Valkey).
  • Mensageria (messagingobs — RabbitMQ, produce/consume com finish(err)).
  • Métricas de negócio (factory/helpers, tenant.id explícito).
  • Checklist de adoção por serviço + regras invioláveis (cardinalidade/PII).
  • Seção do que não está disponível (Mongo, HTTP em Fiber v2).

Qualidade

Todas as assinaturas/snippets foram validados contra a API real da v2 (mergeada no #36). Sem código que não compila.

🤖 Generated with Claude Code

Prescriptive usage guide (docs/USAGE.md) for instrumenting a service with
lib-observability v2: bootstrap (NewTelemetry + ApplyGlobals pitfall),
HTTP (Fiber v3), gRPC (grpcmiddleware), SQL (sqlobs, incl. dbresolver +
separate-pool caveat), cache (redisobs Redis/Valkey), messaging
(messagingobs RabbitMQ), business metrics, an adoption checklist, and the
cardinality/PII rules. All snippets validated against the real v2 API.

Meant to be handed to an AI/engineer to perform the per-service
instrumentation (Fase 3). Mongo + HTTP-on-Fiber-v2 explicitly listed as
not-yet-available.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1
@lerian-studio

lerian-studio commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

🔍 PR Validation Summary

✅ PR Mergeable — no blocking failures

Check Status Blocking
Source Branch ✅ success yes
PR Title ✅ success yes
PR Description ✅ success yes
PR Size ✅ success no
Auto Labels ✅ success no
PR Metadata ✅ success no

🔍 View workflow run

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

O guia docs/USAGE.md passa a prescrever a configuração da telemetria v2, a instrumentação de HTTP, gRPC, SQL, Redis/Valkey e RabbitMQ, métricas de negócio, checklist de adoção, regras de cardinalidade/PII e limitações conhecidas.

Changes

Guia de instrumentação

Layer / File(s) Summary
Bootstrap e instrumentação de entrada
docs/USAGE.md
Define o fluxo OTLP, o bootstrap com tracing.NewTelemetry, o encerramento da telemetria e a instrumentação exclusiva de HTTP Fiber v3 e gRPC.
Integrações de dados e mensageria
docs/USAGE.md
Documenta a instrumentação de SQL, Redis/Valkey e RabbitMQ, incluindo propagação de contexto, métricas de pool e remoção de spans manuais duplicados.
Métricas de negócio e adoção
docs/USAGE.md
Descreve métricas manuais, checklist operacional, validação no Grafana/Mimir, regras de cardinalidade/PII e limitações atuais.
✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch docs/lib-o11y-usage-guide

Comment @coderabbitai help to get the list of available commands.

@gauchito91 gauchito91 changed the title docs(usage): instrumentation guide for lib-observability v2 docs(core): instrumentation guide for lib-observability v2 Jul 23, 2026
@lerian-studio lerian-studio added size/M PR changes 200–499 lines docs Documentation, llms.txt and markdown content labels Jul 23, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/USAGE.md`:
- Line 229: Update the HTTP checklist item in the Fiber v3 section to reference
tm.WithTelemetry(tel) instead of middleware.WithTelemetry, matching the
documented HTTP example while preserving the Fiber version guidance.
- Around line 121-123: Update the usage examples around InstrumentDB,
RegisterDBStatsMetrics, and f.Counter to handle each returned error before
proceeding. Only construct the resolver after both InstrumentDB calls succeed,
defer reg.Unregister() after successful registration, and check the f.Counter
result before calling WithAttributes().AddOne(...), returning or reporting
errors consistently with the examples.
- Around line 31-42: Update the NewTelemetry example to handle initialization
errors by returning or exiting before registering the shutdown defer, preventing
use of a nil tel handle. Define a shutdown context for
ShutdownTelemetryWithContext, or use an existing documented context variable, so
ctx is initialized before the defer.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ed1f7ade-adb3-4cb0-a311-da916b848951

📥 Commits

Reviewing files that changed from the base of the PR and between 944738d and 0af9db7.

📒 Files selected for processing (1)
  • docs/USAGE.md

Comment thread docs/USAGE.md
Comment thread docs/USAGE.md
Comment thread docs/USAGE.md Outdated
- bootstrap: return/exit on NewTelemetry error before the shutdown defer
  (nil handle would panic); define the shutdown ctx.
- sqlobs.RegisterDBStatsMetrics / metrics.Counter: check returned error
  before defer Unregister / chaining.
- adoption checklist: use tm.WithTelemetry(tel) to match the HTTP example.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/USAGE.md`:
- Around line 41-45: Update the production telemetry example around NewTelemetry
to use an HTTPS collector endpoint and set InsecureExporter to false;
alternatively, clearly relabel the configuration as development-only. Ensure the
documented production path does not require ALLOW_INSECURE_OTEL or terminate at
startup.
- Around line 41-46: Add the standard library imports for context and log to the
import block used by the telemetry bootstrap example, so context.Background and
log.Fatalf resolve when the snippet is copied.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1eacdde4-28a2-4c1d-a8b7-da49211de027

📥 Commits

Reviewing files that changed from the base of the PR and between 0af9db7 and a3a3bf8.

📒 Files selected for processing (1)
  • docs/USAGE.md

Comment thread docs/USAGE.md
Comment thread docs/USAGE.md
…eRabbit)

- bootstrap example used DeploymentEnv=production + InsecureExporter=true,
  which makes NewTelemetry return an error (service won't start) unless
  ALLOW_INSECURE_OTEL is set. Switch to https:// endpoint + InsecureExporter
  false, and add a security note explaining the policy + when insecure is
  allowed (development/local only).
- add missing imports (context, log) used by the bootstrap snippet.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1
…oint

Bootstrap example now reads all config from environment variables (the
Helm-injected pattern already used by Lerian services) instead of a literal
URL in code: OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_RESOURCE_SERVICE_NAME/_VERSION/
_DEPLOYMENT_ENVIRONMENT, OTEL_LIBRARY_NAME, ENABLE_TELEMETRY. Endpoint/insecure
are decided per-environment by Helm; the code only calls os.Getenv. Security
note reworded accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/USAGE.md`:
- Line 26: Update the usage documentation and corresponding configuration
snippet to either implement an ENV_NAME fallback when
OTEL_RESOURCE_DEPLOYMENT_ENVIRONMENT is unset, or remove ENV_NAME from the
documented canonical variables; ensure the documented behavior matches the
configuration actually read for DeploymentEnv.
- Around line 38-39: Update the ParseBool handling for ENABLE_TELEMETRY and
OTEL_EXPORTER_OTLP_INSECURE to distinguish unset variables from malformed
non-empty values: retain false only when the environment variable is unset, and
surface or return ParseBool errors for invalid input instead of ignoring them.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f8180878-6bc4-441f-b575-31b041bfd97b

📥 Commits

Reviewing files that changed from the base of the PR and between 47da09d and 6541d5e.

📒 Files selected for processing (1)
  • docs/USAGE.md

Comment thread docs/USAGE.md
Comment thread docs/USAGE.md Outdated
- DeploymentEnv: fall back to ENV_NAME when OTEL_RESOURCE_DEPLOYMENT_ENVIRONMENT
  is unset (both are used across the services' .env), instead of only
  mentioning ENV_NAME in a comment while reading a single var.
- ParseBool: distinguish unset (default false) from a malformed value (return
  error) via a parseBoolEnv helper, so a typo in ENABLE_TELEMETRY /
  OTEL_EXPORTER_OTLP_INSECURE no longer silently disables telemetry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/USAGE.md (1)

70-76: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle ErrEmptyEndpoint separately in this example. NewTelemetry returns a non-nil noop telemetry handle and installs noop globals when the collector endpoint is empty, so this log.Fatalf aborts the service instead of letting the documented fallback run.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/USAGE.md` around lines 70 - 76, Update the error handling around
NewTelemetry to detect ErrEmptyEndpoint separately, allowing the non-nil noop
telemetry handle and installed noop globals to continue through the documented
fallback path; retain log.Fatalf for other initialization errors, and keep the
ShutdownTelemetryWithContext defer safe for the resulting handle.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/USAGE.md`:
- Around line 41-45: Update the boolean environment parsing flow using
os.LookupEnv so only !ok returns false without an error. Remove the v == ""
shortcut, allowing explicitly empty values to reach strconv.ParseBool and return
its parsing error.

---

Outside diff comments:
In `@docs/USAGE.md`:
- Around line 70-76: Update the error handling around NewTelemetry to detect
ErrEmptyEndpoint separately, allowing the non-nil noop telemetry handle and
installed noop globals to continue through the documented fallback path; retain
log.Fatalf for other initialization errors, and keep the
ShutdownTelemetryWithContext defer safe for the resulting handle.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 360e6b27-fa45-4730-9d9a-b287f937d439

📥 Commits

Reviewing files that changed from the base of the PR and between 6541d5e and d34ecb3.

📒 Files selected for processing (1)
  • docs/USAGE.md

Comment thread docs/USAGE.md Outdated
parseBoolEnv now defaults false ONLY for unset vars (!ok). An explicitly set
but empty value (e.g. an empty Helm value) goes to strconv.ParseBool and fails
visibly, so it can't silently disable telemetry or flip exporter security.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
X-Lerian-Ref: 0x1
@gauchito91
gauchito91 merged commit da1cdc1 into develop Jul 23, 2026
6 checks passed
@github-actions
github-actions Bot deleted the docs/lib-o11y-usage-guide branch July 23, 2026 20:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Documentation, llms.txt and markdown content size/M PR changes 200–499 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants