forked from techschool/simplebank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
83 lines (70 loc) · 1.82 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
package gapi
import (
"context"
"net/http"
"time"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func GrpcLogger(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
startTime := time.Now()
result, err := handler(ctx, req)
duration := time.Since(startTime)
statusCode := codes.Unknown
if st, ok := status.FromError(err); ok {
statusCode = st.Code()
}
logger := log.Info()
if err != nil {
logger = log.Error().Err(err)
}
logger.Str("protocol", "grpc").
Str("method", info.FullMethod).
Int("status_code", int(statusCode)).
Str("status_text", statusCode.String()).
Dur("duration", duration).
Msg("received a gRPC request")
return result, err
}
type ResponseRecorder struct {
http.ResponseWriter
StatusCode int
Body []byte
}
func (rec *ResponseRecorder) WriteHeader(statusCode int) {
rec.StatusCode = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}
func (rec *ResponseRecorder) Write(body []byte) (int, error) {
rec.Body = body
return rec.ResponseWriter.Write(body)
}
func HttpLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
startTime := time.Now()
rec := &ResponseRecorder{
ResponseWriter: res,
StatusCode: http.StatusOK,
}
handler.ServeHTTP(rec, req)
duration := time.Since(startTime)
logger := log.Info()
if rec.StatusCode != http.StatusOK {
logger = log.Error().Bytes("body", rec.Body)
}
logger.Str("protocol", "http").
Str("method", req.Method).
Str("path", req.RequestURI).
Int("status_code", rec.StatusCode).
Str("status_text", http.StatusText(rec.StatusCode)).
Dur("duration", duration).
Msg("received a HTTP request")
})
}