-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
77 lines (72 loc) · 1.62 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 logger
import (
"fmt"
"net/http"
"time"
"github.com/fatih/color"
"github.com/goa-go/goa"
)
var (
bold = color.New(color.Bold).SprintFunc()
green = color.New(color.FgGreen).SprintFunc()
red = color.New(color.FgRed).SprintFunc()
yellow = color.New(color.FgYellow).SprintFunc()
cyan = color.New(color.FgCyan).SprintFunc()
)
// New returns the initialized goa-logger instance.
func New() goa.Middleware {
return func(c *goa.Context, next func()) {
start := time.Now()
fmt.Fprintf(
color.Output,
"[%s] <-- %s %s\n",
start.Format("2006-01-02 15:04:05"),
bold(c.Method),
c.URL,
)
defer func() {
if err := recover(); err != nil {
statusCode := 500
if e, ok := err.(goa.Error); ok {
statusCode = e.Code
}
fmt.Fprintf(
color.Output,
"[%s] %s %s %s %s %d%s\n",
time.Now().Format("2006-01-02 15:04:05"),
red("xxx"),
bold(c.Method),
c.Path,
colorStatus(statusCode),
time.Since(start).Nanoseconds()/1e6,
"ms",
)
panic(err)
}
}()
next()
fmt.Fprintf(
color.Output,
"[%s] %s %s %s %s %d%s\n",
time.Now().Format("2006-01-02 15:04:05"),
"-->",
bold(c.Method),
c.Path,
colorStatus(c.GetStatus()),
time.Since(start).Nanoseconds()/1e6,
"ms",
)
}
}
func colorStatus(code int) string {
switch {
case code >= http.StatusOK && code < http.StatusMultipleChoices:
return green(code)
case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
return cyan(code)
case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
return yellow(code)
default:
return red(code)
}
}