Skip to content

Remove nested Loggers in Make #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 38 additions & 8 deletions slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,50 @@ type Logger struct {
exit func(int)
}

// Make creates a logger that writes logs to the passed sinks at LevelInfo.
func (l Logger) flatSinks() []Sink {
sinks := make([]Sink, 0, len(l.sinks))
for _, s := range l.sinks {
switch l2 := s.(type) {
case Logger:
sinks = append(sinks, l2.flatSinks()...)
continue
case *Logger:
sinks = append(sinks, l2.flatSinks()...)
continue
}

sinks = append(sinks, s)
}

return sinks
}

// Make creates a logger that writes logs to the passed sinks.
//
// The name, level and fields are taken from the first Logger passed.
func Make(sinks ...Sink) Logger {
return Logger{
l := Logger{
sinks: sinks,
level: LevelInfo,

exit: os.Exit,
}
l.sinks = l.flatSinks()
for _, s := range sinks {
switch l2 := s.(type) {
case Logger:
l.level = l2.level
l.names = l2.names
l.fields = l2.fields
return l
case *Logger:
l.level = l2.level
l.names = l2.names
l.fields = l2.fields
return l
}
}
return l
}

// Debug logs the msg and fields at LevelDebug.
Expand Down Expand Up @@ -137,12 +173,6 @@ func (l Logger) Named(name string) Logger {
// equal to or above the given level.
func (l Logger) Leveled(level Level) Logger {
l.level = level
l.sinks = append([]Sink(nil), l.sinks...)
for i, s := range l.sinks {
if l2, ok := s.(Logger); ok {
l.sinks[i] = l2.Leveled(level)
}
}
return l
}

Expand Down