-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
108 lines (87 loc) · 2.54 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
package golog
import (
"encoding/json"
"fmt"
"io"
"log"
)
// A Logger produces structured log output in the format defined by Google for GCP logs.
type Logger struct {
logger *log.Logger
fields Fields
}
// NewLogger creates a new logger which outputs to the given `io.Writer`.
// It allows setting fields which are included in every output log entry.
func NewLogger(w io.Writer, fields Fields) *Logger {
return &Logger{
fields: fields,
logger: log.New(w, "", 0),
}
}
// output creates a new log entry and prints it to the logger's output.
func (l *Logger) output(severity level, msg string, req *HTTPRequest, fields Fields) {
countLog()
entry := newEntry(severity, msg, req, fields)
if entry.fields == nil {
entry.fields = make(Fields)
}
for k, v := range l.fields {
f, ok := v.(func() interface{})
if ok {
v = f()
}
entry.fields[k] = v
}
encoded, err := json.Marshal(entry)
if err != nil {
log.Println(err)
fmt.Println(err)
}
l.logger.Println(string(encoded))
}
// AddFields adds new fields to the logger.
// Existing fields might be overwritten.
func (l *Logger) AddFields(newFields Fields) {
if l.fields == nil {
l.fields = make(Fields)
}
for k, v := range newFields {
l.fields[k] = v
}
}
// GetFields returns the fields of the logger.
func (l *Logger) GetFields() Fields {
return l.fields
}
// Debug outputs a debug log message.
func (l *Logger) Debug(msg string, req *HTTPRequest, fields Fields) {
l.output(levelDebug, msg, req, fields)
}
// Info outputs an info log message.
func (l *Logger) Info(msg string, req *HTTPRequest, fields Fields) {
l.output(levelInfo, msg, req, fields)
}
// Notice outputs a notice log message.
func (l *Logger) Notice(msg string, req *HTTPRequest, fields Fields) {
l.output(levelNotice, msg, req, fields)
}
// Warning outputs a warning log message.
func (l *Logger) Warning(msg string, req *HTTPRequest, fields Fields) {
l.output(levelWarning, msg, req, fields)
}
// Error outputs an error log message.
func (l *Logger) Error(msg string, req *HTTPRequest, fields Fields) {
l.output(levelError, msg, req, fields)
}
// Critical outputs a critical log message.
func (l *Logger) Critical(msg string, req *HTTPRequest, fields Fields) {
l.output(levelCritical, msg, req, fields)
}
// Alert outputs an alert log message.
func (l *Logger) Alert(msg string, req *HTTPRequest, fields Fields) {
l.output(levelAlert, msg, req, fields)
}
// Emergency outputs an emergency log message.
func (l *Logger) Emergency(msg string, req *HTTPRequest, fields Fields) {
l.output(levelEmergency, msg, req, fields)
}