Files
kurious/internal/common/xcontext/log.go
2024-04-02 15:23:22 +03:00

59 lines
1.8 KiB
Go

package xcontext
import (
"context"
"log/slog"
)
type ctxLogKey struct{}
type ctxRequestID struct{}
func WithRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, ctxRequestID{}, requestID)
}
func GetRequestID(ctx context.Context) string {
reqid, _ := ctx.Value(ctxRequestID{}).(string)
return reqid
}
type ctxLogAttrStore struct {
attrs []slog.Attr
}
func WithLogFields(ctx context.Context, fields ...slog.Attr) context.Context {
store, _ := ctx.Value(ctxLogKey{}).(ctxLogAttrStore)
store.attrs = append(store.attrs, fields...)
return context.WithValue(ctx, ctxLogKey{}, store)
}
func LogDebug(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) {
log.LogAttrs(ctx, slog.LevelDebug, msg, append(getLogFields(ctx), attrs...)...)
}
func LogInfo(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) {
log.LogAttrs(ctx, slog.LevelInfo, msg, append(getLogFields(ctx), attrs...)...)
}
func LogWarn(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) {
log.LogAttrs(ctx, slog.LevelWarn, msg, append(getLogFields(ctx), attrs...)...)
}
func LogError(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) {
log.LogAttrs(ctx, slog.LevelError, msg, append(getLogFields(ctx), attrs...)...)
}
func LogWithWarnError(ctx context.Context, log *slog.Logger, err error, msg string, attrs ...slog.Attr) {
LogWarn(ctx, log, msg, append(attrs, slog.Any("err", err))...)
}
func LogWithError(ctx context.Context, log *slog.Logger, err error, msg string, attrs ...slog.Attr) {
LogError(ctx, log, msg, append(attrs, slog.Any("err", err))...)
}
func getLogFields(ctx context.Context) []slog.Attr {
store, _ := ctx.Value(ctxLogKey{}).(ctxLogAttrStore)
return store.attrs
}