-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path048.MultiServiceAndLogIdentify.go
More file actions
84 lines (71 loc) · 2.15 KB
/
048.MultiServiceAndLogIdentify.go
File metadata and controls
84 lines (71 loc) · 2.15 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
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
var g errgroup.Group
func Index01(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"msg": "Welcome Server 01",
})
}
func Index02(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"msg": "Welcome Server 02",
})
}
type LogFormatterWithInstanceIdentify struct {
instanceName string
}
func (p *LogFormatterWithInstanceIdentify) defaultLogFormatterWithInstanceIdentify(param gin.LogFormatterParams) string {
var statusColor, methodColor, resetColor string
if param.IsOutputColor() {
statusColor = param.StatusCodeColor()
methodColor = param.MethodColor()
resetColor = param.ResetColor()
}
if param.Latency > time.Minute {
// Truncate in a golang < 1.8 safe way
param.Latency = param.Latency - param.Latency%time.Second
}
return fmt.Sprintf("[GIN] Service:%s |%v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
p.instanceName,
param.TimeStamp.Format("2006/01/02 - 15:04:05"),
statusColor, param.StatusCode, resetColor,
param.Latency,
param.ClientIP,
methodColor, param.Method, resetColor,
param.Path,
param.ErrorMessage,
)
}
// gin.defaultLogFormatter() 是 private 叫不出來
// func (p *LogFormatterWithInstanceIdentify) defaultLogFormatterWithInstanceIdentify2(param gin.LogFormatterParams) string {
// outString := gin.defaultLogFormatter(param)
// strings.Replace(outString, "[GIN]", fmt.Sprintf("[GIN] Service:%s |", p.instanceName), 1)
// return outString
// }
func main() {
g.Go(func() error {
router1 := gin.New()
router1.Use(gin.Recovery())
logFormatter := LogFormatterWithInstanceIdentify{instanceName: "01"}
router1.Use(gin.LoggerWithFormatter(logFormatter.defaultLogFormatterWithInstanceIdentify))
router1.GET("/", Index01)
return router1.Run(":8080")
})
g.Go(func() error {
router2 := gin.New()
router2.Use(gin.Recovery())
logFormatter := LogFormatterWithInstanceIdentify{instanceName: "02"}
router2.Use(gin.LoggerWithFormatter(logFormatter.defaultLogFormatterWithInstanceIdentify))
router2.GET("/", Index02)
return router2.Run(":8081")
})
g.Wait()
}