Store and retrieve loggers from context.Context for request-scoped logging
Velo provides utilities to store loggers in context.Context, enabling request-scoped logging without modifying function signatures throughout your codebase.
In real-world applications, you often want to attach request-specific fields (like request ID, user ID, or trace ID) to all logs within a request’s lifecycle:
Velo provides LogContext and LogContextFields methods that accept a context and automatically extract fields using a ContextExtractor:
// Configure a context extractorlogger := velo.NewWithOptions(os.Stderr, velo.Options{ ContextExtractor: func(ctx context.Context) []velo.Field { fields := []velo.Field{} if requestID, ok := ctx.Value("request_id").(string); ok { fields = append(fields, velo.String("request_id", requestID)) } if userID, ok := ctx.Value("user_id").(int); ok { fields = append(fields, velo.Int("user_id", userID)) } return fields },})// Use context-aware logginglogger.LogContext(ctx, velo.InfoLevel, "user action", "action", "update_profile",)// Automatically includes request_id and user_id from context
Using a ContextExtractor is more efficient than manually calling FromContext because the extractor runs once per log call and caches the extracted fields.
Set up your logger with all request-scoped fields in middleware or at the entry point of your request handler. This ensures all downstream code has access to the enriched logger.
Use typed fields for request-scoped data
When creating request-scoped loggers with WithFields(), use typed fields for better performance:
Be cautious about what fields you extract from context. Avoid logging passwords, tokens, or other sensitive information.
Use ContextExtractor for common patterns
If you consistently extract the same fields from context across your application, configure a ContextExtractor on your logger rather than manually extracting fields in each handler.