38 lines
1017 B
Go
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)
|
|
}
|