Files
telemetry/README.md

71 lines
2.3 KiB
Markdown
Raw Normal View History

# telemetry
OTel SDK bootstrap — wires up TracerProvider, MeterProvider, and LoggerProvider with OTLP gRPC exporters pointed at Grafana Alloy (→ Tempo / Mimir / Loki).
**Tier 5 — import only from application `main` packages. Never import from framework libraries.**
## Why Tier 5
Micro-libs use only the OTel API (`go.opentelemetry.io/otel`) which ships a zero-overhead no-op default. This module activates the real SDK and sets the three OTel globals, so all micro-libs using the global API auto-instrument without knowing about this module.
## Installation
```
require code.nochebuena.dev/go/telemetry v0.1.0
```
## Usage
```go
func main() {
ctx := context.Background()
// Bootstrap telemetry before any other component.
shutdown, err := telemetry.New(ctx, telemetry.Config{
ServiceName: "order-service",
OTLPEndpoint: "alloy:4317",
OTLPInsecure: true, // dev only
})
if err != nil {
log.Fatalf("telemetry: %v", err)
}
defer shutdown(ctx)
// Start the rest of the application…
}
```
## Config
| Field | Env var | Required | Default | Description |
|---|---|---|---|---|
| `ServiceName` | `OTEL_SERVICE_NAME` | ✓ | — | Service name in traces/metrics/logs |
| `ServiceVersion` | `OTEL_SERVICE_VERSION` | | `unknown` | Deployed version |
| `Environment` | `OTEL_ENVIRONMENT` | | `development` | Deployment environment |
| `OTLPEndpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | ✓ | — | OTLP gRPC address (e.g. `alloy:4317`) |
| `OTLPInsecure` | `OTEL_EXPORTER_OTLP_INSECURE` | | `false` | Disable TLS (dev only) |
## What `New` sets up
| Signal | SDK | Exporter | Backend |
|---|---|---|---|
| Traces | `sdktrace.TracerProvider` | OTLP gRPC | Grafana Alloy → Tempo |
| Metrics | `sdkmetric.MeterProvider` | OTLP gRPC | Grafana Alloy → Mimir |
| Logs | `sdklog.LoggerProvider` | OTLP gRPC | Grafana Alloy → Loki |
Also sets `otel.SetTextMapPropagator` with W3C TraceContext + Baggage.
## Shutdown
The returned `func(context.Context) error` flushes all pending telemetry and shuts down the three providers. Always call it before process exit.
```go
defer func() {
shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := shutdown(shutCtx); err != nil {
log.Printf("telemetry shutdown: %v", err)
}
}()
```