summaryrefslogtreecommitdiff
path: root/logging/testingLogger.go
blob: 0f53e6225ba7a23c160a2e52dd9fd0bd5f4ecb85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (C) 2019-2023 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package logging

import (
	"testing"

	"github.com/sirupsen/logrus"
)

// TestLogWriter is an io.Writer that wraps a testing.T (or a testing.B) -- anything written to it gets logged with t.Log(...)
// Being an io.Writer lets us pass it to Logger.SetOutput() in testing code -- this way if we want we can use Go's built-in testing log instead of making a new base.log file for each test.
// As a bonus, the detailed logs produced in a Travis test are now easily accessible and are printed if and only if that particular test fails.
type TestLogWriter struct {
	testing.TB
}

func (tb TestLogWriter) Write(p []byte) (n int, err error) {
	if len(p) == 0 {
		return 0, nil
	}
	if p[len(p)-1] == '\n' {
		// t.Log() does its own line ending, don't need an extra
		p = p[:len(p)-1]
	}
	tb.Log(string(p))
	return len(p), nil
}

// TestingLogWithoutFatalExit is a test-only convenience function to configure logging for testing in situations where Fatal() may be called
// (e.g. in the case of an expected failure)
// Calls to Fatal() will still call any registered exit handlers
func TestingLogWithoutFatalExit(tb testing.TB) Logger {
	l := logrus.New()
	l.ExitFunc = func(code int) {}
	wl := NewWrappedLogger(l)
	wl.SetLevel(Debug)
	wl.SetOutput(TestLogWriter{tb})
	return wl
}

// TestingLog is a test-only convenience function to configure logging for testing
func TestingLog(tb testing.TB) Logger {
	l := NewLogger()
	l.SetLevel(Debug)
	l.SetOutput(TestLogWriter{tb})
	return l
}