Context fields
Attach request or job metadata to log records.
Context fields keep request metadata close to the log record without adding parameters to every logging method.
Use them for values that belong to the current operation rather than the logger itself: request IDs, trace IDs, user IDs, tenant IDs, job IDs, and similar metadata.
ctx := logy.WithValue(context.Background(), "traceId", "anyTraceId")
ctx = logy.WithValue(ctx, "spanId", "anySpanId")
log.I(ctx, "info message")WithValue returns a new context and copies existing fields. Prefer it when the
context may be shared across goroutines.
PutValue mutates the existing context. Use it only when that mutation is local
and safe for the current execution path.
Passing context through code
Keep the context parameter on functions that already represent a request, message, or job boundary.
func CreateUser(ctx context.Context, user User) error {
log := logy.Get()
log.I(ctx, "creating user {}", user.ID)
return nil
}This keeps the logger stable while the operation-specific values travel through the call stack.
Console output
When the formatter includes context fields, trace and span values appear next to the timestamp. That makes request logs easier to scan without changing every log message.
2023-03-19 20:18:10.062 [anyTraceId,anySpanId] INFO github.com/codnect/logy/test : info message
2023-03-19 20:18:10.062 [anyTraceId,anySpanId] WARN github.com/codnect/logy/test : warning message
2023-03-19 20:18:10.062 [anyTraceId,anySpanId] ERROR github.com/codnect/logy/test : error message
2023-03-19 20:18:10.062 [anyTraceId,anySpanId] DEBUG github.com/codnect/logy/test : debug message
2023-03-19 20:18:10.062 [anyTraceId,anySpanId] TRACE github.com/codnect/logy/test : trace message