package logger import ( "fmt" "io" "log/slog" "os" "strings" "go.uber.org/zap/exp/zapslog" "go.uber.org/zap/zapcore" ) type Format string const ( FormatJSON Format = "json" FormatConsole Format = "console" ) const ( DefaultLevel = slog.LevelInfo DefaultFormat = FormatJSON ) type options struct { writer io.Writer level slog.Level format Format name string } type Option func(*options) func WithWriter(writer io.Writer) Option { return func(opts *options) { if writer != nil { opts.writer = writer } } } func WithLevel(level slog.Level) Option { return func(opts *options) { opts.level = level } } func WithFormat(format Format) Option { return func(opts *options) { if format != "" { opts.format = format } } } func WithName(name string) Option { return func(opts *options) { opts.name = name } } func New(options ...Option) *slog.Logger { opts := optionsConfig() for _, option := range options { option(&opts) } encoderCfg := zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "logger", CallerKey: "caller", MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.RFC3339NanoTimeEncoder, EncodeDuration: zapcore.StringDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } var encoder zapcore.Encoder if opts.format == FormatConsole { encoder = zapcore.NewConsoleEncoder(encoderCfg) } else { encoder = zapcore.NewJSONEncoder(encoderCfg) } core := zapcore.NewCore(encoder, zapcore.AddSync(opts.writer), zapLevel(opts.level)) handlerOptions := make([]zapslog.HandlerOption, 0, 1) if opts.name != "" { handlerOptions = append(handlerOptions, zapslog.WithName(opts.name)) } return slog.New(zapslog.NewHandler(core, handlerOptions...)) } func optionsConfig() options { return options{ writer: os.Stdout, level: DefaultLevel, format: DefaultFormat, } } func ParseLevel(raw string) (slog.Level, error) { var level slog.Level if err := level.UnmarshalText([]byte(strings.TrimSpace(raw))); err != nil { return 0, fmt.Errorf("%q: %w", raw, ErrUnknownLevel) } return level, nil } func ParseFormat(raw string) (Format, error) { switch Format(strings.ToLower(strings.TrimSpace(raw))) { case FormatJSON: return FormatJSON, nil case FormatConsole: return FormatConsole, nil default: return "", fmt.Errorf("%q: %w", raw, ErrUnknownFormat) } } func zapLevel(level slog.Level) zapcore.Level { switch { case level < slog.LevelInfo: return zapcore.DebugLevel case level < slog.LevelWarn: return zapcore.InfoLevel case level < slog.LevelError: return zapcore.WarnLevel default: return zapcore.ErrorLevel } }