-
Notifications
You must be signed in to change notification settings - Fork 7
/
logger.go
81 lines (72 loc) · 1.42 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
package neko
import (
"log"
"os"
"time"
)
var (
green = "\033[32m"
white = "\033[37m"
yellow = "\033[33m"
red = "\033[31m"
blue = "\033[34m"
magenta = "\033[35m"
cyan = "\033[36m"
reset = "\033[0m"
)
func Logger() HandlerFunc {
stdlogger := log.New(os.Stdout, "", 0)
return func(ctx *Context) {
// Start timer
start := time.Now()
// Process request
ctx.Next()
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := ctx.ClientIP()
method := ctx.Req.Method
statusCode := ctx.Writer.Status()
statusColor := colorForStatus(statusCode)
methodColor := colorForMethod(method)
stdlogger.Printf("%s[%s]%s %v |%s %3d %s| %12v | %s |%s %-5s %s %s",
blue, ctx.Engine.AppName, reset,
end.Format("2006/01/02 - 15:04:05"),
statusColor, statusCode, reset,
latency,
clientIP,
methodColor, method, reset,
ctx.Req.URL.Path,
)
}
}
func colorForStatus(code int) string {
switch {
case code >= 200 && code <= 299:
return green
case code >= 300 && code <= 399:
return white
case code >= 400 && code <= 499:
return yellow
default:
return red
}
}
func colorForMethod(method string) string {
switch {
case method == "GET":
return blue
case method == "POST":
return cyan
case method == "PUT":
return yellow
case method == "DELETE":
return red
case method == "PATCH":
return green
case method == "HEAD":
return magenta
default:
return white
}
}