-
Notifications
You must be signed in to change notification settings - Fork 10
/
logger.go
231 lines (186 loc) · 5.82 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Mechanism for handling application level logging
package memfs
import (
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
//===========================================================================
// Log Level Type
//===========================================================================
// LogLevel characterizes the severity of the log message.
type LogLevel int
// Severity levels of log messages.
const (
LevelDebug LogLevel = 1 + iota
LevelInfo
LevelWarn
LevelError
LevelFatal
)
// String representations of the various log levels.
var levelNames = []string{
"DEBUG", "INFO", "WARN", "ERROR", "FATAL",
}
// String representation of the log level.
func (level LogLevel) String() string {
return levelNames[level-1]
}
// LevelFromString parses a string and returns the LogLevel
func LevelFromString(level string) LogLevel {
// Perform string cleanup for matching
level = strings.ToUpper(level)
level = strings.Trim(level, " ")
switch level {
case "DEBUG":
return LevelDebug
case "INFO":
return LevelInfo
case "WARN":
return LevelWarn
case "WARNING":
return LevelWarn
case "ERROR":
return LevelError
case "FATAL":
return LevelFatal
default:
return LevelInfo
}
}
//===========================================================================
// Logger wrapper for log.Logger and logging initialization methods
//===========================================================================
// Logger wraps the log.Logger to write to a file on demand and to specify a
// miminum severity that is allowed for writing.
type Logger struct {
Level LogLevel // The minimum severity to log to
logger *log.Logger // The wrapped logger for concurrent logging
output io.WriteCloser // Handle to the open log file or writer object
}
// InitLogger creates a Logger object by passing a configuration that contains
// the minimum log level and an optional path to write the log out to.
func InitLogger(path string, level string) (*Logger, error) {
newLogger := new(Logger)
newLogger.Level = LevelFromString(level)
// If a path is specified create a handle to the writer.
if path != "" {
var err error
newLogger.output, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
} else {
newLogger.output = os.Stdout
}
newLogger.logger = log.New(newLogger.output, "", 0)
return newLogger, nil
}
// Close the logger and any open file handles.
func (logger *Logger) Close() error {
if err := logger.output.Close(); err != nil {
return err
}
return nil
}
// GetHandler returns the io.Writer object that is on the logger.
func (logger *Logger) GetHandler() io.Writer {
return logger.output
}
// SetHandler sets a new io.WriteCloser object onto the logger
func (logger *Logger) SetHandler(writer io.WriteCloser) {
logger.output = writer
logger.logger.SetOutput(writer)
}
//===========================================================================
// Logging handlers
//===========================================================================
// Log a message at the appropriate severity. The Log method behaves as a
// format function, and a layout string can be passed with arguments.
// The current logging format is "%(level)s [%(jsontime)s]: %(message)s"
func (logger *Logger) Log(layout string, level LogLevel, args ...interface{}) {
// Only log if the log level matches the log request
if level >= logger.Level {
msg := fmt.Sprintf(layout, args...)
msg = fmt.Sprintf("%-7s [%s]: %s", level, time.Now().Format(JSONDateTime), msg)
// If level is fatal then log fatal.
if level == LevelFatal {
logger.logger.Fatalln(msg)
} else {
logger.logger.Println(msg)
}
}
}
// Debug message helper function
func (logger *Logger) Debug(msg string, args ...interface{}) {
logger.Log(msg, LevelDebug, args...)
}
// Info message helper function
func (logger *Logger) Info(msg string, args ...interface{}) {
logger.Log(msg, LevelInfo, args...)
}
// Warn message helper function
func (logger *Logger) Warn(msg string, args ...interface{}) {
logger.Log(msg, LevelWarn, args...)
}
// Error message helper function
func (logger *Logger) Error(msg string, args ...interface{}) {
logger.Log(msg, LevelError, args...)
}
// Fatal message helper function
func (logger *Logger) Fatal(msg string, args ...interface{}) {
logger.Log(msg, LevelFatal, args...)
}
//===========================================================================
// HTTP logging handler for the C2S API and web interface
//===========================================================================
// :method :url :status :response-time ms - :res[content-length]
const webLogFmt = "c2s %s %s %d %s - %d"
// WebLogger is a decorator for http handlers to record HTTP requests using
// the logger API and syntax, which must be passed in as the first argument.
func WebLogger(log *Logger, inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lw := &responseLogger{w: w}
inner.ServeHTTP(lw, r)
log.Info(webLogFmt, r.Method, r.RequestURI, lw.Status(), time.Since(start), lw.Size())
})
}
// responseLogger is a wrapper of http.ResponseWriter that keeps track of its
// HTTP status code and body size for reporting to the console.
type responseLogger struct {
w http.ResponseWriter
status int
size int
}
func (l *responseLogger) Header() http.Header {
return l.w.Header()
}
func (l *responseLogger) Write(b []byte) (int, error) {
if l.status == 0 {
l.status = http.StatusOK
}
size, err := l.w.Write(b)
l.size += size
return size, err
}
func (l *responseLogger) WriteHeader(s int) {
l.w.WriteHeader(s)
l.status = s
}
func (l *responseLogger) Status() int {
return l.status
}
func (l *responseLogger) Size() int {
return l.size
}
func (l *responseLogger) Flush() {
f, ok := l.w.(http.Flusher)
if ok {
f.Flush()
}
}