-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
73 lines (62 loc) · 1.51 KB
/
logger.go
File metadata and controls
73 lines (62 loc) · 1.51 KB
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
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"io"
"log"
"time"
)
// LoggerWithWriter instance a Logger middleware with the specified writter buffer.
// Example: os.Stdout, a file opened in write mode, a socket...
func LoggerWithWriter(out io.Writer, flag string, notlogged ...string) gin.HandlerFunc {
var skip map[string]struct{}
if length := len(notlogged); length > 0 {
skip = make(map[string]struct{}, length)
for _, path := range notlogged {
skip[path] = struct{}{}
}
}
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
// Process request
c.Next()
// Log only when path is not being skipped
if _, ok := skip[path]; !ok {
// Stop timer
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
if query != "" {
fmt.Fprintf(out, "[kvraft] %v | %3d | %13v | %s | %-7s %s?%s\n%s",
end.Format("2006/01/02 - 15:04:05"),
statusCode,
latency,
clientIP,
method,
path,
query,
comment,
)
} else {
fmt.Fprintf(out, "[kvraft] %v | %3d | %13v | %s | %-7s %s\n%s",
end.Format("2006/01/02 - 15:04:05"),
statusCode,
latency,
clientIP,
method,
path,
comment,
)
}
}
}
}
func InitServerLog(out io.Writer, flag string) *log.Logger {
return log.New(out, flag, log.LstdFlags)
}