-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
77 lines (67 loc) · 1.61 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
package cotton
import (
"fmt"
"io"
"os"
"time"
)
// LoggerConf config for logger
type LoggerConf struct {
Formatter func(param LoggerFormatterParam, ctx *Context) string
Writer io.Writer
}
// LoggerFormatterParam param to formatter
type LoggerFormatterParam struct {
Host string
Method string
StatusCode int
TimeStamp time.Time
Latency time.Duration
ClientIP string
Path string
}
var defaultLogFormatter = func(param LoggerFormatterParam, ctx *Context) string {
return fmt.Sprintf("[INFO] %v\t%13s %6s %3d %10v %s \n",
param.TimeStamp.Format("2006/01/02 15:04:05"),
param.ClientIP,
param.Method,
param.StatusCode,
param.Latency,
param.Host+param.Path,
)
}
var defaultWriter io.Writer = os.Stdout
// Logger logger middleware
func Logger() HandlerFunc {
return LoggerWidthConf(LoggerConf{})
}
// SetWriter set default writer
func SetWriter(writer io.Writer) {
defaultWriter = writer
}
// LoggerWidthConf get logger with config
func LoggerWidthConf(conf LoggerConf) HandlerFunc {
formatter := conf.Formatter
writer := conf.Writer
if nil == formatter {
formatter = defaultLogFormatter
}
if nil == writer {
writer = defaultWriter
}
debugPrint("use logger middleware")
return func(ctx *Context) {
timeStart := time.Now()
ctx.Next()
param := LoggerFormatterParam{
Method: ctx.Request.Method,
Path: ctx.Request.RequestURI,
TimeStamp: time.Now(),
StatusCode: ctx.Response.GetStatusCode(),
ClientIP: ctx.ClientIP(),
Host: ctx.Request.Host,
}
param.Latency = param.TimeStamp.Sub(timeStart)
fmt.Fprint(writer, formatter(param, ctx))
}
}