ContextLogger implements contextual logging using slog by embedding itself into context.Context's.
Making it effortless to maintain consistent log context throughout your application's call stack.
It has the following features:
- Context-Embedded Logging - Logger travels with your context.Context, eliminating manual logger passing
- slog Familiarity - Built on top of Go's standard log/slog package with a familiar API
- Structured Logging - Support for key-value pairs and nested groups for organized log output
- Highly Configurable - Customize log levels, handlers, formatters, and output destinations
- Middleware Ready - Built-in HTTP middleware for automatic request logging, and more coming soon!
- Multiple Handlers - Support for JSON, text, and custom log formats. Basically, everything that slog supports
- Performance Focused - Minimal overhead with efficient context propagation
Traditional logging often requires passing a logger instance through your entire call stack or using a global logger that lacks request-specific context. Context Logger solves this by:
- Embedding the logger in context - Access your logger anywhere you have a context.Context
- Automatic context accumulation - Build up contextual information as requests flow through layers
- Cleaner function signatures - No need to pass logger as a parameter to every function
Use go get:
go get github.com/pablovarg/contextloggerThen import the contextlogger package into your code:
import "github.com/pablovarg/contextlogger"ctx := context.Background()
// Embed a logger into the context
ctx = contextlogger.EmbedLogger(ctx)
// Update the stored context
contextlogger.UpdateContext(ctx, "id", user.ID, "email", user.Email)
// Create groups for different parts of your code,
// and update the context as above inside this group
processUser(contextlogger.WithGroup(ctx, "userProcess"))
// To print the whole accumulated context
contextlogger.LogWithContext(ctx, slog.LevelInfo, "user information")This project is currently open to contributions from the community, some things you can work on:
- Support for different logging libraries
- Include a middleware for your favorite framework
- Anything else you can imagine