2 Star 1 Fork 0

法马智慧/fmgo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
kratos.go 2.34 KB
一键复制 编辑 原始数据 按行查看 历史
零海 提交于 2022-10-17 17:57 . kratos日志调整
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)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/fmpt/fmgo.git
git@gitee.com:fmpt/fmgo.git
fmpt
fmgo
fmgo
v1.2.11

搜索帮助