Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Created August 26, 2024 19:47
Show Gist options
  • Save juanpabloaj/b95ebf1080c0d6edbee59159876505ff to your computer and use it in GitHub Desktop.
Save juanpabloaj/b95ebf1080c0d6edbee59159876505ff to your computer and use it in GitHub Desktop.
Go slog, example with context handler
package main
import (
"context"
"log/slog"
"os"
)
type contextKey string
const transactionIDKey = contextKey("transactionID")
func contextWithTransactionID(ctx context.Context, transactionID string) context.Context {
return context.WithValue(ctx, transactionIDKey, transactionID)
}
type ContextHandler struct {
slog.Handler
}
func (h *ContextHandler) Handle(ctx context.Context, r slog.Record) error {
if transactionID, ok := ctx.Value(transactionIDKey).(string); ok {
r.AddAttrs(slog.String("tx_id", transactionID))
}
return h.Handler.Handle(ctx, r)
}
func deepProcess(ctx context.Context) {
slog.DebugContext(ctx, "inside the deep process")
}
func main() {
var logLevel = new(slog.LevelVar)
logger := slog.New(&ContextHandler{slog.NewTextHandler(
os.Stdout, &slog.HandlerOptions{Level: logLevel})})
slog.SetDefault(logger)
slog.Debug("Debug 00 ignored")
slog.Info("Info 00")
logLevel.Set(slog.LevelDebug)
slog.Debug("Debug 01")
slog.Info("Info 01")
ctx := context.Background()
slog.DebugContext(ctx, "debug 02")
// get or create transaction ID or event ID, and add it to the context
ctx = contextWithTransactionID(ctx, "tx_or_event_or_alert_id_12345")
slog.DebugContext(ctx, "debug 03")
deepProcess(ctx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment