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

109 lines
2.6 KiB

4 years ago
package logging
import (
"context"
"fmt"
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/grpc"
"github.com/go-kratos/kratos/v2/transport/http"
)
// Server is an server logging middleware.
func Server(l log.Logger) middleware.Middleware {
logger := log.NewHelper("middleware/logging", l)
4 years ago
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
var (
path string
method string
params string
component string
4 years ago
)
if info, ok := http.FromServerContext(ctx); ok {
component = "HTTP"
4 years ago
path = info.Request.RequestURI
method = info.Request.Method
params = info.Request.Form.Encode()
4 years ago
} else if info, ok := grpc.FromServerContext(ctx); ok {
component = "gRPC"
4 years ago
path = info.FullMethod
method = "POST"
params = req.(fmt.Stringer).String()
4 years ago
}
reply, err := handler(ctx, req)
if err != nil {
logger.Errorw(
4 years ago
"kind", "server",
"component", component,
4 years ago
"path", path,
"method", method,
"params", params,
4 years ago
"code", errors.Code(err),
"error", err.Error(),
)
return nil, err
}
logger.Infow(
4 years ago
"kind", "server",
"component", component,
4 years ago
"path", path,
"method", method,
"params", params,
4 years ago
"code", 0,
)
return reply, nil
}
}
}
// Client is an client logging middleware.
func Client(l log.Logger) middleware.Middleware {
logger := log.NewHelper("middleware/logging", l)
4 years ago
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (interface{}, error) {
var (
path string
method string
params string
component string
4 years ago
)
if info, ok := http.FromClientContext(ctx); ok {
component = "HTTP"
path = info.Request.RequestURI
method = info.Request.Method
params = info.Request.Form.Encode()
4 years ago
} else if info, ok := grpc.FromClientContext(ctx); ok {
path = info.FullMethod
method = "POST"
component = "gRPC"
params = req.(fmt.Stringer).String()
4 years ago
}
reply, err := handler(ctx, req)
if err != nil {
logger.Errorw(
4 years ago
"kind", "client",
"component", component,
"path", path,
"method", method,
"params", params,
4 years ago
"code", errors.Code(err),
"error", err.Error(),
)
return nil, err
}
logger.Infow(
4 years ago
"kind", "client",
"component", component,
"path", path,
"method", method,
"params", params,
4 years ago
"code", 0,
)
return reply, nil
}
}
}