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
| package middleware
import (
"fmt"
"net/http"
"time"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/transport"
)
func Server(logger log.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
code int32
reason string
kind string
operation string
)
ctx := r.Context()
startTime := time.Now()
if info, ok := transport.FromServerContext(ctx); ok {
kind = info.Kind().String()
operation = info.Operation()
}
next.ServeHTTP(w, r)
if se := errors.FromError(nil); se != nil {
code = se.Code
reason = se.Reason
}
level, stack := extractError(nil)
_ = log.WithContext(ctx, logger).Log(level,
"kind", "server",
"component", kind,
"operation", operation,
"args", extractArgs(r),
"code", code,
"reason", reason,
"stack", stack,
"latency", time.Since(startTime).Seconds(),
)
})
}
}
// extractArgs returns the string of the req
func extractArgs(req interface{}) string {
if stringer, ok := req.(fmt.Stringer); ok {
return stringer.String()
}
return fmt.Sprintf("%+v", req)
}
// extractError returns the string of the error
func extractError(err error) (log.Level, string) {
if err != nil {
return log.LevelError, fmt.Sprintf("%+v", err)
}
return log.LevelInfo, ""
}
|