3737 path string
3838 level * slog.LevelVar
3939 attributes []Attr
40+ match Match
4041 }
4142
4243 // Option configures Logger during initialization.
@@ -50,6 +51,11 @@ type (
5051 Attr = slog.Attr
5152
5253 Format = string
54+
55+ // Match is a function that determines whether a log message
56+ // should be logged. Return true to log the message, false to
57+ // skip it.
58+ Match func (level Level , msg string , attrs []Attr ) bool
5359)
5460
5561var (
@@ -101,6 +107,15 @@ func WithFormat(format Format) Option {
101107 }
102108}
103109
110+ // WithMatch sets a match function that determines whether a log
111+ // message should be logged. If the match returns false, the message
112+ // is skipped.
113+ func SkipMatch (match Match ) Option {
114+ return func (l * Logger ) {
115+ l .match = match
116+ }
117+ }
118+
104119// Any creates a key-value attribute with any data type.
105120func Any (k string , v any ) Attr {
106121 return slog .Any (k , v )
@@ -198,21 +213,25 @@ func NewLogger(options ...Option) *Logger {
198213}
199214
200215// With returns a new Logger with additional attributes, keeping the
201- // original Logger’ s name and settings.
216+ // original Logger' s name and settings.
202217func (l * Logger ) With (attrs ... Attr ) * Logger {
203- return NewLogger (
218+ opts := [] Option {
204219 WithName (l .path ),
205220 WithOutput (l .output ),
206221 WithLevel (l .level .Level ()),
207222 WithAttributes (
208223 append (l .attributes , attrs ... )... ,
209224 ),
210225 WithFormat (l .format ),
211- )
226+ }
227+ if l .match != nil {
228+ opts = append (opts , SkipMatch (l .match ))
229+ }
230+ return NewLogger (opts ... )
212231}
213232
214233// Named returns a new Logger with a modified name, appending the
215- // given name to the current Logger’ s path.
234+ // given name to the current Logger' s path.
216235func (l * Logger ) Named (name string , options ... Option ) * Logger {
217236 newPath := l .path
218237 if newPath != "" {
@@ -226,6 +245,9 @@ func (l *Logger) Named(name string, options ...Option) *Logger {
226245 WithAttributes (l .attributes ... ),
227246 WithFormat (l .format ),
228247 }
248+ if l .match != nil {
249+ inheritedOptions = append (inheritedOptions , SkipMatch (l .match ))
250+ }
229251
230252 options = append (inheritedOptions , options ... )
231253 options = append (options , WithName (newPath ))
@@ -236,6 +258,10 @@ func (l *Logger) Named(name string, options ...Option) *Logger {
236258// Log logs a message at the specified level with optional attributes,
237259// adding trace and span IDs if the context has a span.
238260func (l * Logger ) Log (ctx context.Context , level Level , msg string , args ... Attr ) {
261+ if l .match != nil && ! l .match (level , msg , args ) {
262+ return
263+ }
264+
239265 span := trace .SpanFromContext (ctx )
240266
241267 if span .IsRecording () {
0 commit comments