Skip to content

Commit

Permalink
logger: add function to mock logger with debug enabled (#15050)
Browse files Browse the repository at this point in the history
* logger: add function to mock logger with debug enabled

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* logger: add test for function which mocks debug logger

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

---------

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>
  • Loading branch information
olivercalder authored Feb 8, 2025
1 parent a17231c commit ba9ef8e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
12 changes: 11 additions & 1 deletion logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,19 @@ func NoGuardDebugf(format string, v ...interface{}) {
// MockLogger replaces the existing logger with a buffer and returns
// the log buffer and a restore function.
func MockLogger() (buf *bytes.Buffer, restore func()) {
return mockLogger(&LoggerOptions{})
}

// MockDebugLogger replaces the existing logger with a buffer and returns
// the log buffer and a restore function. The logger records debug messages.
func MockDebugLogger() (buf *bytes.Buffer, restore func()) {
return mockLogger(&LoggerOptions{ForceDebug: true})
}

func mockLogger(opts *LoggerOptions) (buf *bytes.Buffer, restore func()) {
buf = &bytes.Buffer{}
oldLogger := logger
l, err := New(buf, DefaultFlags, &LoggerOptions{})
l, err := New(buf, DefaultFlags, opts)
if err != nil {
panic(err)
}
Expand Down
7 changes: 7 additions & 0 deletions logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,10 @@ func (s *LogSuite) TestForceDebug(c *C) {
l.Debug("xyzzy")
c.Check(buf.String(), testutil.Contains, `DEBUG: xyzzy`)
}

func (s *LogSuite) TestMockDebugLogger(c *C) {
logbuf, restore := logger.MockDebugLogger()
defer restore()
logger.Debugf("xyzzy")
c.Check(logbuf.String(), testutil.Contains, "DEBUG: xyzzy")
}

0 comments on commit ba9ef8e

Please sign in to comment.