-
Notifications
You must be signed in to change notification settings - Fork 12
/
logkit.go
83 lines (71 loc) · 1.66 KB
/
logkit.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
package hera
import (
"log/syslog"
"net/http"
"time"
"fmt"
)
var Logger *XLogger = nil
const (
LevelDebug = iota
LevelInfo
LevelWarn
LevelError
)
type XLogger struct {
logName string
logLevel int
logWriter *syslog.Writer
}
func (this *XLogger) Init(logName string, logLevel int) {
this.logName = logName
this.logLevel = logLevel
this.logWriter = getWriter(this.logName)
}
func NewLogger(logName string, logLevel int) *XLogger {
if Logger == nil {
Logger = &XLogger{}
Logger.Init(logName, LevelDebug)
}
return Logger
}
func getWriter(logName string) *syslog.Writer {
writer, _ := syslog.New(syslog.LOG_INFO|syslog.LOG_LOCAL6, logName)
return writer
}
func (this *XLogger) Logger() *syslog.Writer {
if this.logName == "" {
panic("XLogger log name missing")
}
if this.logWriter == nil {
panic("XLogger log writer missing")
}
return this.logWriter
}
func (this *XLogger) Debug(str string) {
if this.logLevel <= LevelDebug {
this.Logger().Info(" [debug] " + str)
}
}
func (this *XLogger) Info(str string) {
if this.logLevel <= LevelInfo {
this.Logger().Info(" [info] " + str)
}
}
func (this *XLogger) Warn(str string) {
if this.logLevel <= LevelWarn {
this.Logger().Info(" [warn] " + str)
}
}
func (this *XLogger) Error(str string) {
if this.logLevel <= LevelError {
this.Logger().Info(" [error] " + str)
}
}
func (this *XLogger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
this.Info(fmt.Sprintf("Started %s %s", r.Method, r.URL.Path))
next(rw, r)
res := rw.(ResponseWriter)
this.Info(fmt.Sprintf("Completed %v %s in %v", res.Status(), http.StatusText(res.Status()), time.Since(start)))
}