summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/mattermost/logr/v2/stdlogger.go
blob: 50171b3df8cb2e8ad0cbe881022201fdcfebf980 (plain) (blame)
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
package logr

import (
	"log"
	"os"
	"strings"
)

// NewStdLogger creates a standard logger backed by a Logr instance.
// All log records are emitted with the specified log level.
func NewStdLogger(level Level, logger Logger) *log.Logger {
	adapter := newStdLogAdapter(logger, level)
	return log.New(adapter, "", 0)
}

// RedirectStdLog redirects output from the standard library's package-global logger
// to this logger at the specified level and with zero or more Field's. Since Logr already
// handles caller annotations, timestamps, etc., it automatically disables the standard
// library's annotations and prefixing.
// A function is returned that restores the original prefix and flags and resets the standard
// library's output to os.Stderr.
func (lgr *Logr) RedirectStdLog(level Level, fields ...Field) func() {
	flags := log.Flags()
	prefix := log.Prefix()
	log.SetFlags(0)
	log.SetPrefix("")

	logger := lgr.NewLogger().With(fields...)
	adapter := newStdLogAdapter(logger, level)
	log.SetOutput(adapter)

	return func() {
		log.SetFlags(flags)
		log.SetPrefix(prefix)
		log.SetOutput(os.Stderr)
	}
}

type stdLogAdapter struct {
	logger Logger
	level  Level
}

func newStdLogAdapter(logger Logger, level Level) *stdLogAdapter {
	return &stdLogAdapter{
		logger: logger,
		level:  level,
	}
}

// Write implements io.Writer
func (a *stdLogAdapter) Write(p []byte) (int, error) {
	s := strings.TrimSpace(string(p))
	a.logger.Log(a.level, s)
	return len(p), nil
}