You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/middleware/logging/logging.go

76 lines
1.8 KiB

4 years ago
package logging
import (
"context"
"fmt"
"go.opentelemetry.io/otel/trace"
4 years ago
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport"
4 years ago
)
// Server is an server logging middleware.
func Server(logger log.Logger) middleware.Middleware {
4 years ago
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
reply, err = handler(ctx, req)
if tr, ok := transport.FromContext(ctx); ok {
switch tr.Kind {
case transport.KindHTTP:
httpServerLog(logger, ctx, extractArgs(req), err)
case transport.KindGRPC:
grpcServerLog(logger, ctx, extractArgs(req), err)
}
4 years ago
}
return
4 years ago
}
}
}
// Client is an client logging middleware.
func Client(logger log.Logger) middleware.Middleware {
4 years ago
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
reply, err = handler(ctx, req)
if tr, ok := transport.FromContext(ctx); ok {
switch tr.Kind {
case transport.KindHTTP:
httpClientLog(logger, ctx, extractArgs(req), err)
case transport.KindGRPC:
grpcClientLog(logger, ctx, extractArgs(req), err)
}
4 years ago
}
return
4 years ago
}
}
}
func extractArgs(req interface{}) string {
if stringer, ok := req.(fmt.Stringer); ok {
return stringer.String()
}
return fmt.Sprintf("%+v", req)
}
func extractTrace(ctx context.Context) (traceID, spanID string) {
span := trace.SpanContextFromContext(ctx)
if span.HasTraceID() {
traceID = span.TraceID().String()
}
if span.HasSpanID() {
spanID = span.SpanID().String()
}
return
}
func extractError(err error) (code int, errMsg string) {
if err != nil {
code = errors.Code(err)
errMsg = fmt.Sprintf("%+v", err)
}
return
}