aboutsummaryrefslogtreecommitdiff
path: root/logging/log.go
blob: ce3fb747b182b95c616690fd576e24a7b7d9cf0b (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
63
64
65
66
package logging

import (
	"io"
	"log"
)

type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
}

type NopLogger struct{}

func (NopLogger) Print(v ...interface{})                 {}
func (NopLogger) Printf(format string, v ...interface{}) {}
func (NopLogger) Println(v ...interface{})               {}

type Level int

const (
	LQuiet Level = iota
	LError
	LWarn
	LInfo
	LDebug
)

type Log struct {
	err, warn, info, debug Logger
}

func (l Log) Error() Logger { return l.err }
func (l Log) Warn() Logger  { return l.warn }
func (l Log) Info() Logger  { return l.info }
func (l Log) Debug() Logger { return l.debug }

func buildLogger(out io.Writer, prefix string, lWant, lHave Level) Logger {
	if lWant <= lHave {
		return log.New(out, prefix, log.LstdFlags)
	} else {
		return NopLogger{}
	}
}

func NewLog(out io.Writer, level Level) *Log {
	l := new(Log)

	l.err = buildLogger(out, "[Err]", LError, level)
	l.warn = buildLogger(out, "[Warn]", LWarn, level)
	l.info = buildLogger(out, "[Info]", LInfo, level)
	l.debug = buildLogger(out, "[Debug]", LDebug, level)

	return l
}

// NewNopLog creates a logger that is completly silent / doesn't log on any log level
func NewNopLog() *Log {
	return &Log{
		NopLogger{},
		NopLogger{},
		NopLogger{},
		NopLogger{},
	}
}