forked from micro-plat/hydra
/
logging.go
57 lines (50 loc) · 1.7 KB
/
logging.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
package middleware
import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/micro-plat/hydra/conf"
"github.com/micro-plat/lib4go/logger"
)
//Logging 记录日志
func Logging(conf *conf.MetadataConf) gin.HandlerFunc {
return func(ctx *gin.Context) {
start := time.Now()
setStartTime(ctx)
setMetadataConf(ctx, conf)
p := ctx.Request.URL.Path
if ctx.Request.URL.RawQuery != "" {
p = p + "?" + ctx.Request.URL.RawQuery
}
uuid := getUUID(ctx)
setUUID(ctx, uuid)
log := logger.GetSession(conf.Name, uuid, "biz", strings.Replace(strings.Trim(ctx.Request.URL.Path, "/"), "/", "_", -1))
log.Info(conf.Type+".request", ctx.Request.Method, p, "from", ctx.ClientIP())
setLogger(ctx, log)
ctx.Next()
v, _ := getResponseRaw(ctx)
statusCode := ctx.Writer.Status()
if statusCode >= 200 && statusCode < 400 {
log.Info(conf.Type+".response", ctx.Request.Method, p, statusCode, getExt(ctx), time.Since(start), v)
} else {
log.Error(conf.Type+".response", ctx.Request.Method, p, statusCode, getExt(ctx), time.Since(start), v)
}
context := getCTX(ctx)
if context != nil {
defer context.Close()
}
}
}
func wLogHead(ctx *gin.Context, p string) {
conf := getMetadataConf(ctx)
getLogger(ctx).Info(conf.Type+".request", ctx.Request.Method, p, "from", ctx.ClientIP())
}
func wLogTail(ctx *gin.Context, p string, start time.Time) {
conf := getMetadataConf(ctx)
statusCode := getCTX(ctx).Response.GetStatus()
if statusCode >= 200 && statusCode < 400 {
getLogger(ctx).Info(conf.Type+".response", ctx.Request.Method, p, statusCode, getExt(ctx), time.Since(start))
} else {
getLogger(ctx).Error(conf.Type+".response", ctx.Request.Method, p, statusCode, getExt(ctx), time.Since(start))
}
}