Documentation
¶
Overview ¶
Package loggingctx provides structured logging support through context propagation.
This package includes: - adding slog attributes to a context - retrieving slog attributes from a context - initializing zap logger for slog with automatic context attribute extraction
Examples:
// Add attributes to context
ctx = loggingctx.AddLogAttr(ctx, "user_id", userId)
ctx = loggingctx.AddLogAttr(ctx, "request_id", requestId)
// Initialize zap logger for slog with context attribute support
logger, err := loggingctx.InitLogger("dev")
if err != nil {
// handle error
}
slog.SetDefault(logger)
// Later in the request flow, context attributes are automatically included
// No need to manually pass GetLogAttrs
slog.InfoContext(ctx, "User action completed")
Example ¶
package main
import (
"context"
"log"
"log/slog"
"github.com/gitrus/digikeeper-bot/pkg/loggingctx"
)
func main() {
ctx := context.Background()
ctx = loggingctx.AddLogAttr(ctx, "user_id", 345)
ctx = loggingctx.AddLogAttr(ctx, "request_id", "12345")
ctx = loggingctx.AddLogAttrs(
ctx,
[]slog.Attr{slog.Int("user_id", 346), slog.String("user_name", "John Doe")},
)
logger, err := loggingctx.InitLogger("dev")
if err != nil {
log.Fatalf("Failed to initialize logger: %v", err)
}
slog.SetDefault(logger)
// Later in the request flow, retrieve all attributes for logging
slog.InfoContext(ctx, "User action completed", loggingctx.GetLogAttrs(ctx)...)
}
Output:
Index ¶
Examples ¶
Constants ¶
const LogAttrsKey contextKey = "LogAttrsKey"
LogAttrsKey is the context key used for storing logging attributes
Variables ¶
This section is empty.
Functions ¶
func AddLogAttr ¶
AddLogAttr adds a logging attribute to the provided context
func AddLogAttrs ¶
AddLogAttr adds a logging attributes list to the provided context
func GetLogAttrs ¶
GetLogAttrs retrieves logging attributes slice from the context
Types ¶
type ContextHandler ¶
type ContextHandler struct {
// contains filtered or unexported fields
}
ContextHandler is a custom slog handler that includes context attributes from LogAttrsKey
func (*ContextHandler) Handle ¶
Handle implements slog.Handler.Handle by adding attributes from context automatically