-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgin.go
69 lines (56 loc) · 1.58 KB
/
gin.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
package logformatter
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/golang/protobuf/ptypes"
"google.golang.org/genproto/googleapis/logging/type"
"google.golang.org/genproto/googleapis/logging/v2"
)
type (
// GinLog represents the configuration to setup gin logger
GinLog struct {
Severity ltype.LogSeverity
}
)
var defaultGinLog = GinLog{Severity: ltype.LogSeverity_INFO}
// GinLogSeverity sets the severity for the GinLog
func GinLogSeverity(s ltype.LogSeverity) func(*GinLog) {
return func(g *GinLog) {
g.Severity = s
}
}
// NewGinLogFormatter takes zero or one GinOption function and applis to GinLog.
func NewGinLogFormatter(Options ...func(*GinLog)) gin.LogFormatter {
config := defaultGinLog
for _, o := range Options {
o(&config)
}
return func(params gin.LogFormatterParams) string {
sLog := Stackdriver{
LogEntry: logging.LogEntry{
HttpRequest: <ype.HttpRequest{
RequestMethod: params.Method,
RequestUrl: params.Request.URL.String(),
Status: int32(params.StatusCode),
UserAgent: params.Request.UserAgent(),
RemoteIp: params.ClientIP,
Protocol: params.Request.Proto,
ResponseSize: int64(params.BodySize),
},
Severity: config.Severity,
},
}
if !params.TimeStamp.IsZero() {
ts, _ := ptypes.TimestampProto(params.TimeStamp)
sLog.Timestamp = ts
}
if int64(params.Latency) != 0 {
sLog.HttpRequest.Latency = ptypes.DurationProto(params.Latency)
}
result, err := json.Marshal(&sLog)
if err != nil {
return err.Error() + "\n"
}
return string(result) + "\n"
}
}