-
Notifications
You must be signed in to change notification settings - Fork 13
/
logger.go
162 lines (140 loc) · 3.97 KB
/
logger.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package logger
import (
"errors"
"io"
"log"
"os"
"regexp"
"time"
"github.com/circonus-labs/circonus-unified-agent/internal"
"github.com/circonus-labs/circonus-unified-agent/internal/rotate"
"github.com/influxdata/wlog"
)
var prefixRegex = regexp.MustCompile("^[DIWE]!")
const (
LogTargetFile = "file"
LogTargetStderr = "stderr"
)
// LogConfig contains the log configuration settings
type LogConfig struct {
// will set the log level to DEBUG
Debug bool
// will set the log level to ERROR
Quiet bool
// stderr, stdout, file or eventlog (Windows only)
LogTarget string
// will direct the logging output to a file. Empty string is
// interpreted as stderr. If there is an error opening the file the
// logger will fallback to stderr
Logfile string
// will rotate when current file at the specified time interval
RotationInterval internal.Duration
// will rotate when current file size exceeds this parameter.
RotationMaxSize internal.Size
// maximum rotated files to keep (older ones will be deleted)
RotationMaxArchives int
}
type Creator interface {
CreateLogger(config LogConfig) (io.Writer, error)
}
var loggerRegistry map[string]Creator
func registerLogger(name string, loggerCreator Creator) {
if loggerRegistry == nil {
loggerRegistry = make(map[string]Creator)
}
loggerRegistry[name] = loggerCreator
}
type cuaLog struct {
writer io.Writer
internalWriter io.Writer
}
func (t *cuaLog) Write(b []byte) (n int, err error) {
var line []byte
if !prefixRegex.Match(b) {
line = append([]byte(time.Now().UTC().Format(time.RFC3339)+" I! "), b...)
} else {
line = append([]byte(time.Now().UTC().Format(time.RFC3339)+" "), b...)
}
return t.writer.Write(line)
}
func (t *cuaLog) Close() error {
stdErrWriter := os.Stderr
// avoid closing stderr
if t.internalWriter != stdErrWriter {
closer, isCloser := t.internalWriter.(io.Closer)
if !isCloser {
return errors.New("the underlying writer cannot be closed")
}
return closer.Close()
}
return nil
}
// newCUAWriter returns a logging-wrapped writer.
func newCUAWriter(w io.Writer) io.Writer {
return &cuaLog{
writer: wlog.NewWriter(w),
internalWriter: w,
}
}
// SetupLogging configures the logging output.
func SetupLogging(config LogConfig) {
newLogWriter(config)
}
type cuaLogCreator struct {
}
func (t *cuaLogCreator) CreateLogger(config LogConfig) (io.Writer, error) {
var writer, defaultWriter io.Writer
defaultWriter = os.Stderr
switch config.LogTarget {
case LogTargetFile:
if config.Logfile != "" {
var err error
if writer, err = rotate.NewFileWriter(config.Logfile, config.RotationInterval.Duration, config.RotationMaxSize.Size, config.RotationMaxArchives); err != nil {
log.Printf("E! Unable to open %s (%s), using stderr", config.Logfile, err)
writer = defaultWriter
}
} else {
writer = defaultWriter
}
case LogTargetStderr, "":
writer = defaultWriter
default:
log.Printf("E! Unsupported logtarget: %s, using stderr", config.LogTarget)
writer = defaultWriter
}
return newCUAWriter(writer), nil
}
// Keep track what is actually set as a log output, because log package doesn't provide a getter.
// It allows closing previous writer if re-set and have possibility to test what is actually set
var actualLogger io.Writer
func newLogWriter(config LogConfig) io.Writer {
log.SetFlags(0)
if config.Debug {
wlog.SetLevel(wlog.DEBUG)
}
if config.Quiet {
wlog.SetLevel(wlog.ERROR)
}
if !config.Debug && !config.Quiet {
wlog.SetLevel(wlog.INFO)
}
var logWriter io.Writer
if logCreator, ok := loggerRegistry[config.LogTarget]; ok {
logWriter, _ = logCreator.CreateLogger(config)
}
if logWriter == nil {
logWriter, _ = (&cuaLogCreator{}).CreateLogger(config)
}
if closer, isCloser := actualLogger.(io.Closer); isCloser {
closer.Close()
}
log.SetOutput(logWriter)
actualLogger = logWriter
return logWriter
}
func init() {
tlc := &cuaLogCreator{}
registerLogger("", tlc)
registerLogger(LogTargetStderr, tlc)
registerLogger(LogTargetFile, tlc)
}