Created
August 26, 2024 19:47
-
-
Save juanpabloaj/b95ebf1080c0d6edbee59159876505ff to your computer and use it in GitHub Desktop.
Go slog, example with context handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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