@@ -18,6 +18,7 @@ package log
1818
1919import (
2020 "context"
21+ "fmt"
2122 "io"
2223 "log/slog"
2324 "os"
3132 // flexible output configuration.
3233 Logger struct {
3334 logger * slog.Logger
35+ format Format
3436 output io.Writer
3537 path string
3638 level * slog.LevelVar
@@ -46,13 +48,18 @@ type (
4648 // Attr represents an attribute (key-value pair) added to log
4749 // entries for structured logging.
4850 Attr = slog.Attr
51+
52+ Format = string
4953)
5054
5155var (
5256 LevelInfo = slog .LevelInfo
5357 LevelError = slog .LevelError
5458 LevelWarn = slog .LevelWarn
5559 LevelDebug = slog .LevelDebug
60+
61+ FormatJSON Format = "json"
62+ FormatText Format = "text"
5663)
5764
5865// WithLevel sets the logging level for the Logger.
@@ -86,6 +93,12 @@ func WithAttributes(attrs ...Attr) Option {
8693 }
8794}
8895
96+ func WithFormat (format Format ) Option {
97+ return func (l * Logger ) {
98+ l .format = format
99+ }
100+ }
101+
89102// Any creates a key-value attribute with any data type.
90103func Any (k string , v any ) Attr {
91104 return slog .Any (k , v )
@@ -143,20 +156,34 @@ func NewLogger(options ...Option) *Logger {
143156 l := & Logger {
144157 output : os .Stderr ,
145158 level : new (slog.LevelVar ),
159+ format : FormatJSON ,
146160 }
147161
148162 for _ , option := range options {
149163 option (l )
150164 }
151165
152- handler := slog .NewJSONHandler (
153- l .output ,
154- & slog.HandlerOptions {
155- Level : l .level ,
156- },
157- ).WithAttrs (l .attributes )
166+ var handler slog.Handler
167+ switch l .format {
168+ case FormatText :
169+ handler = slog .NewTextHandler (
170+ l .output ,
171+ & slog.HandlerOptions {
172+ Level : l .level ,
173+ },
174+ )
175+ case FormatJSON :
176+ handler = slog .NewJSONHandler (
177+ l .output ,
178+ & slog.HandlerOptions {
179+ Level : l .level ,
180+ },
181+ )
182+ default :
183+ panic (fmt .Errorf ("unsupported format %s for logger %s" , l .format , l .path ))
184+ }
158185
159- l .logger = slog .New (handler )
186+ l .logger = slog .New (handler . WithAttrs ( l . attributes ) )
160187
161188 return l
162189}
@@ -171,6 +198,7 @@ func (l *Logger) With(attrs ...Attr) *Logger {
171198 WithAttributes (
172199 append (l .attributes , attrs ... )... ,
173200 ),
201+ WithFormat (l .format ),
174202 )
175203}
176204
@@ -187,6 +215,7 @@ func (l *Logger) Named(name string, options ...Option) *Logger {
187215 WithOutput (l .output ),
188216 WithLevel (l .level .Level ()),
189217 WithAttributes (l .attributes ... ),
218+ WithFormat (l .format ),
190219 }
191220
192221 options = append (inheritedOptions , options ... )
0 commit comments