This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstandard_logger.go
73 lines (60 loc) · 1.68 KB
/
standard_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
package log
import (
"encoding/json"
"io"
"sync"
"time"
)
// StandardLogger is a structured logger that is thread safe.
type StandardLogger struct {
output io.Writer
globalFields Fields
mutex sync.Mutex
}
// NewStandardLogger initializes a new StandardLogger object and returns it.
// output is the output that the log messages are written to.
// globalFields are the fields that are written in every log message.
func NewStandardLogger(output io.Writer, globalFields Fields) *StandardLogger {
return &StandardLogger{
output: output,
globalFields: globalFields,
}
}
// Info writes a log message at an info level.
func (l *StandardLogger) Info(fields Fields) error {
fields["level"] = "info"
return l.write(fields)
}
// Error writes a log message at an error level.
func (l *StandardLogger) Error(fields Fields) error {
fields["level"] = "error"
return l.write(fields)
}
// Debug writes a log message at a debug level.
func (l *StandardLogger) Debug(fields Fields) error {
fields["level"] = "debug"
return l.write(fields)
}
// write combines the globalFields and the passed fields, then
// marshals them to JSON. A new line character is then added to the end
// of the message and finally written to the output.
func (l *StandardLogger) write(fields Fields) error {
for k, v := range l.globalFields {
fields[k] = v
}
for k := range fields {
if err, ok := fields[k].(error); ok {
fields[k] = err.Error()
}
}
fields["time"] = time.Now().Format("2006-01-02 15:04:05")
data, err := json.Marshal(fields)
if err != nil {
return err
}
data = append(data, []byte("\n")...)
l.mutex.Lock()
defer l.mutex.Unlock()
_, err = l.output.Write(data)
return err
}