tercul-backend/internal/observability/logger.go
google-labs-jules[bot] 3bcd8d08f5 feat: Implement observability stack
This commit introduces a comprehensive observability stack to the application, addressing a key objective from the TODO list.

The following features have been implemented:

- **Centralized Logging:** Replaced the existing custom logger with `zerolog` for structured, leveled, and performant logging. The logger is configured to output human-friendly console logs in development and JSON logs in production.

- **Distributed Tracing:** Integrated OpenTelemetry to provide distributed tracing capabilities. A new middleware has been added to create spans for all incoming HTTP requests, and the trace context is propagated.

- **Prometheus Metrics:** Added Prometheus metrics to monitor HTTP request latency and total request counts. A new `/metrics` endpoint is exposed on port 9090 to serve these metrics.

- **Request ID:** Implemented a middleware to add a unique request ID to every incoming request and response, improving traceability.

The new observability components are encapsulated in the `internal/observability` package, and the existing `internal/platform/log` package has been refactored to be a backward-compatible wrapper around the new logger.

The main application entry point (`cmd/api/main.go`) has been updated to initialize and gracefully shut down the new observability components.
2025-10-03 16:43:01 +00:00

54 lines
1.5 KiB
Go

package observability
import (
"context"
"os"
"time"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/trace"
)
// Logger is a wrapper around zerolog.Logger to provide a consistent logging interface.
type Logger struct {
*zerolog.Logger
}
// NewLogger creates a new Logger instance.
// It writes to a human-friendly console in "development" environment,
// and writes JSON to stdout otherwise.
func NewLogger(serviceName, environment string) *Logger {
var logger zerolog.Logger
if environment == "development" {
logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().
Timestamp().
Str("service", serviceName).
Logger()
} else {
zerolog.TimeFieldFormat = time.RFC3339
logger = zerolog.New(os.Stdout).With().
Timestamp().
Str("service", serviceName).
Logger()
}
return &Logger{&logger}
}
// Ctx returns a new logger with context-specific fields, such as trace and span IDs.
func (l *Logger) Ctx(ctx context.Context) *Logger {
log := l.Logger // log is a *zerolog.Logger
span := trace.SpanFromContext(ctx)
if span.SpanContext().IsValid() {
// .Logger() returns a value, not a pointer.
// We create a new logger value...
newLogger := log.With().
Str("trace_id", span.SpanContext().TraceID().String()).
Str("span_id", span.SpanContext().SpanID().String()).
Logger()
// ...and then use its address.
log = &newLogger
}
// `log` is now the correct *zerolog.Logger, so we wrap it.
return &Logger{log}
}