From 394efb65155b6e41af207b841dc5960f9bf782e5 Mon Sep 17 00:00:00 2001 From: Randy Reddig Date: Tue, 29 Oct 2024 15:53:36 -0600 Subject: [PATCH] internal/logging: prototype slog logging --- internal/logging/logging.go | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 internal/logging/logging.go diff --git a/internal/logging/logging.go b/internal/logging/logging.go new file mode 100644 index 00000000..a9f1fdff --- /dev/null +++ b/internal/logging/logging.go @@ -0,0 +1,43 @@ +package logging + +import ( + "context" + "io" + "log" + "log/slog" +) + +// Logger returns an opinionated logger for the given level. +func Logger(out io.Writer, level slog.Level) *slog.Logger { + return slog.New(textHandler(out, level)) +} + +func textHandler(out io.Writer, level slog.Level) slog.Handler { + return slog.NewTextHandler(out, &slog.HandlerOptions{ + Level: level, + }) +} + +// TODO: need this? +func textLogger(out io.Writer) *log.Logger { + return log.New(out, "", 0) +} + +// DiscardLogger returns a [slog.Logger] that discards all output. +func DiscardLogger() *slog.Logger { + return slog.New(DiscardHandler()) +} + +// DiscardHandler returns a [slog.Handler] that discards all output. +// It is an implementation of https://github.com/golang/go/issues/62005. +func DiscardHandler() slog.Handler { + return (*discardHandler)(nil) +} + +type discardHandler struct { + slog.Handler +} + +func (*discardHandler) Enabled(_ context.Context, _ slog.Level) bool { + return false +}