代码拉取完成,页面将自动刷新
package logx
import (
"context"
"fmt"
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/errors"
klog "github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport"
"time"
)
type KratosLogger struct {
*Logger
}
// NewKratosLogger returns a new kratos logger
func NewKratosLogger(logger *Logger) klog.Logger {
return KratosLogger{logger}
}
func (l KratosLogger) makeMessage(msg string) string {
// 前缀
prefix := fmt.Sprintf("kratos@%s/context", kratos.Release)
return fmt.Sprintf("%-30s%s", prefix, msg)
}
func (l KratosLogger) Log(level klog.Level, msg ...interface{}) error {
var value []interface{}
for i := 1; i < len(msg); i += 2 {
value = append(value, msg[i])
}
data := Format(value...)
data = l.makeMessage(data)
switch level {
case klog.LevelDebug:
l.Logger.Debug(data)
case klog.LevelInfo:
l.Logger.Info(data)
case klog.LevelWarn:
l.Logger.Warn(data)
case klog.LevelError:
l.Logger.Error(data)
case klog.LevelFatal:
l.Logger.Fatal(data)
}
return nil
}
// KratosServer is an server logging middleware.
func KratosServer(logger klog.Logger) middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
var (
code int32
reason string
kind string
operation string
)
startTime := time.Now()
if info, ok := transport.FromServerContext(ctx); ok {
kind = info.Kind().String()
operation = info.Operation()
}
reply, err = handler(ctx, req)
if se := errors.FromError(err); se != nil {
code = se.Code
reason = se.Reason
}
level, _ := extractError(err)
_ = klog.WithContext(ctx, logger).Log(level,
"msg",
fmt.Sprintf("[Kratos] %3d | %13v | %10s | %-7s %s\t%s",
code,
time.Since(startTime),
"server",
kind,
operation,
reason,
),
)
return
}
}
}
// extractError returns the string of the error
func extractError(err error) (klog.Level, string) {
if err != nil {
return klog.LevelError, fmt.Sprintf("%+v", err)
}
return klog.LevelInfo, ""
}
// 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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。