sp2-verify-1770324794/pkg/logging/worker.go
jordan 9867230ca9
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/manual/woodpecker Pipeline was successful
Initialize project from skeleton template
2026-02-05 20:53:15 +00:00

38 lines
1017 B
Go

package logging
import (
"context"
"github.com/google/uuid"
)
// WorkerContext creates a context with trace and request IDs for background work.
// Workers and cron jobs don't receive HTTP requests, so they need to generate
// their own correlation IDs for log tracing.
//
// Usage:
//
// func (w *Worker) ProcessJob(ctx context.Context, job Job) error {
// ctx = logging.WorkerContext(ctx, "order-processor")
// logger := logging.FromContext(ctx)
// logger.Info("processing job", "job_id", job.ID)
// // ... all downstream logs include trace_id and request_id
// }
func WorkerContext(ctx context.Context, component string) context.Context {
traceID := uuid.New().String()
requestID := uuid.New().String()
ctx = WithTraceID(ctx, traceID)
ctx = WithRequestID(ctx, requestID)
// If there's a logger in context, enrich it
logger := FromContext(ctx)
enriched := logger.With(
"trace_id", traceID,
"request_id", requestID,
"component", component,
)
return NewContext(ctx, enriched)
}