Go言語のslogで何も出力しないloggerを作る(discard)
code:go
package main
import (
"context"
"golang.org/x/exp/slog"
"net/http"
)
type nopHandler struct{}
var _ slog.Handler = (*nopHandler)(nil)
func (h *nopHandler) Enabled(ctx context.Context, level slog.Level) bool {
return false
}
func (h *nopHandler) Handle(ctx context.Context, record slog.Record) error {
return nil
}
func (h *nopHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return h
}
func (h *nopHandler) WithGroup(name string) slog.Handler {
return h
}
var nopLogger = slog.New(&nopHandler{})
func main() {
logger := nopLogger
logger.Info("hey!", "count", 1)
logger.Error("failed to do something", "err", http.ErrHijacked)
}