Skip to content

Commit

Permalink
feat(log): sub-logger with prefix
Browse files Browse the repository at this point in the history
Creates a sub-logger with the given prefix.

Fixes: #36
  • Loading branch information
aymanbagabas committed Mar 8, 2023
1 parent 7ba0790 commit 99fa380
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,13 @@ func (l *Logger) With(keyvals ...interface{}) *Logger {
return &sl
}

// WithPrefix returns a new logger with the given prefix.
func (l *Logger) WithPrefix(prefix string) *Logger {
sl := l.With()
sl.SetPrefix(prefix)
return sl
}

// Debug prints a debug message.
func (l *Logger) Debug(msg interface{}, keyvals ...interface{}) {
l.log(DebugLevel, msg, keyvals...)
Expand Down
26 changes: 26 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,29 @@ func TestLogFormatter(t *testing.T) {
})
}
}

func TestLogWithPrefix(t *testing.T) {
var buf bytes.Buffer
cases := []struct {
name string
expected string
prefix string
msg string
}{
{
name: "with prefix",
expected: "INFO prefix: info\n",
prefix: "prefix",
msg: "info",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
buf.Reset()
l := New(&buf)
l.SetPrefix(c.prefix)
l.Info(c.msg)
assert.Equal(t, c.expected, buf.String())
})
}
}
5 changes: 5 additions & 0 deletions pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ func With(keyvals ...interface{}) *Logger {
return defaultLogger.With(keyvals...)
}

// WithPrefix returns a new logger with the given prefix.
func WithPrefix(prefix string) *Logger {
return defaultLogger.WithPrefix(prefix)
}

// Helper marks the calling function as a helper
// and skips it for source location information.
// It's the equivalent of testing.TB.Helper().
Expand Down
5 changes: 5 additions & 0 deletions pkg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,8 @@ func TestFormatter(t *testing.T) {
Info("info")
assert.Equal(t, "{\"lvl\":\"info\",\"msg\":\"info\"}\n", buf.String())
}

func TestWithPrefix(t *testing.T) {
l := WithPrefix("test")
assert.Equal(t, "test", l.prefix)
}

0 comments on commit 99fa380

Please sign in to comment.