log package provides structured logging functionality with context support, built on top of Go’s standard log/slog package.
Logger Overview
Platforma’s logger automatically extracts and logs context values like trace IDs, service names, and user IDs. It supports both JSON and text output formats with structured key-value pairs.Global Logger
The package provides a default global logger:SetDefault
void
Sets the default logger used by package-level logging functions.
Creating Loggers
New
*slog.Logger
Creates a new slog.Logger with the specified configuration.Parameters:
w(io.Writer): Output destination (e.g., os.Stdout, file)loggerType(string): Logger format - “json” or “text”level(slog.Level): Minimum log level (LevelDebug, LevelInfo, LevelWarn, LevelError)contextKeys(map[string]any): Additional context keys to extract from context
Logging Methods
The logger provides both context-aware and simple logging methods. Always prefer context-aware methods for better traceability.Context-Aware Methods
void
Logs a debug-level message with context values.
void
Logs an info-level message with context values.
void
Logs a warning-level message with context values.
void
Logs an error-level message with context values.
Simple Methods
These methods don’t use context values:Context Keys
The logger automatically extracts these context keys:contextKey
Domain name for domain-driven architecture.
contextKey
Unique trace ID for request tracking.
contextKey
Name of the service handling the request.
contextKey
Name of the startup task being executed.
contextKey
User ID for user-specific operations.
contextKey
Worker ID for queue processor workers.
TraceIDMiddleware
HTTP middleware that adds trace IDs to requests.Constructor
*TraceIDMiddleware
Creates a new TraceID middleware.Parameters:
contextKey(any): Context key to store trace ID (nil = use TraceIDKey)header(string): HTTP header name (empty = use “Platforma-Trace-Id”)
Wrap
http.Handler
Wraps an HTTP handler to add trace IDs to requests.The middleware:
- Generates a unique trace ID (UUID)
- Adds it to the request context
- Sets it in the response header
- Passes the request to the next handler
Example Usage
Basic Logging
With Trace IDs
HTTP Server with Trace Middleware
Custom Logger Configuration
Output Formats
Text format:Multiple Context Values
Best Practices
- Always use context-aware methods (e.g.,
InfoContext) instead of simple methods - Add trace IDs to all requests for distributed tracing
- Use structured logging with key-value pairs instead of string interpolation
- Include relevant context like user IDs, request IDs, and error details
- Use appropriate log levels: Debug for detailed info, Info for normal operations, Warn for concerning situations, Error for actual errors