-
Notifications
You must be signed in to change notification settings - Fork 6
/
logger.go
97 lines (85 loc) · 2.23 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
package log
import (
"fmt"
"io"
"time"
"github.com/gin-gonic/gin"
)
// Logger is a middleware that will write the logs to gin.DefaultWriter
// By default gin.DefaultWriter = os.Stdout
func Logger(fileName string, maxdays int) gin.HandlerFunc {
if fileName == "" {
return LoggerWithWriter(gin.DefaultWriter)
}
fw := new(fileLogWriter)
fw.FileName = fileName
fw.MaxDays = maxdays
_, err := fw.createLogFile()
if err != nil {
panic(err)
}
return LoggerWithWriter(fw)
}
// LoggerWithHide is a middleware that will hide the values of the given headers when logging
// Must specify all headers, password is not default here
// Default writer is used
func LoggerWithHide(hideValues []string) gin.HandlerFunc {
return loggerCommon(gin.DefaultWriter, hideValues)
}
// LoggerWithWriter is a middleware with the specified writer buffer.
// Example: os.Stdout, a file opened in write mode, a socket...
func LoggerWithWriter(out io.Writer) gin.HandlerFunc {
return loggerCommon(out, []string{"password"})
}
func loggerCommon(out io.Writer, hideValues []string) gin.HandlerFunc {
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
// Process request
c.Next()
statusCode := c.Writer.Status()
// if (strings.HasPrefix(path, "/system/") || strings.HasPrefix(path, "/assets/")) && statusCode < 400 {
// return
// }
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
formValues := c.Request.URL.Query()
if formValues == nil {
formValues = make(map[string][]string)
}
for k, v := range c.Request.Form {
formValues[k] = v
}
if len(formValues) > 0 {
for formValue, _ := range formValues {
for _, hideValue := range hideValues {
if formValue == hideValue {
formValues[formValue] = []string{"***"}
}
}
}
fmt.Fprintf(out, "[GIN] %v | %3d | %11v | %s |%-7s %s\n Params: %v \n",
end.Format("2006/01/02 15:04:05"),
statusCode,
latency,
clientIP,
method,
path,
formValues,
)
} else {
fmt.Fprintf(out, "[GIN] %v | %3d | %11v | %s |%-7s %s\n",
end.Format("2006/01/02 15:04:05"),
statusCode,
latency,
clientIP,
method,
path,
)
}
}
}