提交 bbbda169 authored 作者: mooncake's avatar mooncake

update

上级 f1fb00e9
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/pkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/sgorm" "gitlab.wanzhuangkj.com/tush/xpkg/pkg/sgorm"
"gitlab.wanzhuangkj.com/tush/xpkg/pkg/sgorm/mysql" "gitlab.wanzhuangkj.com/tush/xpkg/pkg/sgorm/mysql"
"gitlab.wanzhuangkj.com/tush/xpkg/xutils" utils "gitlab.wanzhuangkj.com/tush/xpkg/xutils"
) )
func InitMysql(dbConfig *config.Database) (*sgorm.DB, error) { func InitMysql(dbConfig *config.Database) (*sgorm.DB, error) {
......
...@@ -22,7 +22,7 @@ import ( ...@@ -22,7 +22,7 @@ import (
retryutils "gitlab.wanzhuangkj.com/tush/xpkg/xutils/retryutils" retryutils "gitlab.wanzhuangkj.com/tush/xpkg/xutils/retryutils"
) )
const defaultTimeout = 30 * time.Second const defaultTimeout = 60 * time.Second
type Request struct { type Request struct {
cli *http.Client cli *http.Client
......
...@@ -192,14 +192,14 @@ func checkNil() { ...@@ -192,14 +192,14 @@ func checkNil() {
func InitZapWriter(logger *zap.Logger) *ZapWriter { func InitZapWriter(logger *zap.Logger) *ZapWriter {
return &ZapWriter{ return &ZapWriter{
logger: logger, L: logger,
level: logger.Level(), level: logger.Level(),
} }
} }
type ZapWriter struct { type ZapWriter struct {
logger *zap.Logger L *zap.Logger
level zapcore.Level // 日志级别(如 Info、Error) level zapcore.Level // 日志级别(如 Info、Error)
} }
// 实现 io.Writer 接口 // 实现 io.Writer 接口
...@@ -207,9 +207,9 @@ func (w *ZapWriter) Write(p []byte) (n int, err error) { ...@@ -207,9 +207,9 @@ func (w *ZapWriter) Write(p []byte) (n int, err error) {
msg := strings.TrimSuffix(string(p), "\n") // 去除 Gin 日志自带的换行符 msg := strings.TrimSuffix(string(p), "\n") // 去除 Gin 日志自带的换行符
switch w.level { switch w.level {
case zapcore.ErrorLevel: case zapcore.ErrorLevel:
w.logger.Error(msg) w.L.Error(msg)
default: default:
w.logger.Info(msg) w.L.Info(msg)
} }
return len(p), nil return len(p), nil
} }
......
...@@ -3,12 +3,14 @@ package glog ...@@ -3,12 +3,14 @@ package glog
import ( import (
"context" "context"
"errors"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"go.uber.org/zap" "go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
) )
...@@ -17,15 +19,16 @@ const ( ...@@ -17,15 +19,16 @@ const (
) )
type gormLogger struct { type gormLogger struct {
gLog *zap.Logger gLog *zap.Logger
requestIDKey string requestIDKey string
logLevel logger.LogLevel IgnoreRecordNotFoundError bool
logLevel logger.LogLevel
} }
// NewCustomGormLogger custom gorm logger // NewCustomGormLogger custom gorm logger
func NewCustomGormLogger(l *zap.Logger, requestIDKey string, logLevel logger.LogLevel) logger.Interface { func NewCustomGormLogger(l *zap.Logger, requestIDKey string, logLevel logger.LogLevel, opts ...zap.Option) logger.Interface {
if l == nil { if l == nil {
l, _ = zap.NewProduction() l, _ = zap.NewProduction(opts...)
} }
if requestIDKey == "" { if requestIDKey == "" {
requestIDKey = "X-Request-ID" requestIDKey = "X-Request-ID"
...@@ -34,9 +37,10 @@ func NewCustomGormLogger(l *zap.Logger, requestIDKey string, logLevel logger.Log ...@@ -34,9 +37,10 @@ func NewCustomGormLogger(l *zap.Logger, requestIDKey string, logLevel logger.Log
logLevel = logger.Info logLevel = logger.Info
} }
return &gormLogger{ return &gormLogger{
gLog: l, gLog: l,
requestIDKey: requestIDKey, requestIDKey: requestIDKey,
logLevel: logLevel, logLevel: logLevel,
IgnoreRecordNotFoundError: true,
} }
} }
...@@ -97,14 +101,24 @@ func (l *gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql ...@@ -97,14 +101,24 @@ func (l *gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql
sql = clearSql(sql) sql = clearSql(sql)
if err != nil { if err != nil {
l.gLog.Warn("[gorm]", if errors.Is(err, gorm.ErrRecordNotFound) && l.IgnoreRecordNotFoundError {
zap.Error(err), l.gLog.Info("[gorm]",
zap.String("sql", sql), zap.String("sql", sql),
rowsField, rowsField,
zap.String("cost", cost), zap.String("cost", cost),
fileLineField, fileLineField,
requestIDField(ctx, l.requestIDKey), requestIDField(ctx, l.requestIDKey),
) )
} else {
l.gLog.Warn("[gorm]",
zap.Error(err),
zap.String("sql", sql),
rowsField,
zap.String("cost", cost),
fileLineField,
requestIDField(ctx, l.requestIDKey),
)
}
return return
} }
......
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"database/sql" "database/sql"
"log" "log"
"os" "os"
"time"
"github.com/uptrace/opentelemetry-go-extra/otelgorm" "github.com/uptrace/opentelemetry-go-extra/otelgorm"
mysqlDriver "gorm.io/driver/mysql" mysqlDriver "gorm.io/driver/mysql"
...@@ -83,12 +84,12 @@ func gormConfig(o *options) *gorm.Config { ...@@ -83,12 +84,12 @@ func gormConfig(o *options) *gorm.Config {
// print SQL // print SQL
if o.isLog { if o.isLog {
if o.gLog == nil { if o.gLog == nil {
config.Logger = logger.Default.LogMode(o.logLevel) config.Logger = defaultLogger().LogMode(o.logLevel)
} else { } else {
config.Logger = glog.NewCustomGormLogger(o.gLog, o.requestIDKey, o.logLevel) config.Logger = glog.NewCustomGormLogger(o.gLog, o.requestIDKey, o.logLevel)
} }
} else { } else {
config.Logger = logger.Default.LogMode(logger.Silent) config.Logger = defaultLogger().LogMode(logger.Silent)
} }
// print only slow queries // print only slow queries
...@@ -96,9 +97,10 @@ func gormConfig(o *options) *gorm.Config { ...@@ -96,9 +97,10 @@ func gormConfig(o *options) *gorm.Config {
config.Logger = logger.New( config.Logger = logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // use the standard output asWriter log.New(os.Stdout, "\r\n", log.LstdFlags), // use the standard output asWriter
logger.Config{ logger.Config{
SlowThreshold: o.slowThreshold, SlowThreshold: o.slowThreshold,
Colorful: true, Colorful: true,
LogLevel: logger.Warn, // set the logging level, only above the specified level will output the slow query log LogLevel: logger.Warn, // set the logging level, only above the specified level will output the slow query log
IgnoreRecordNotFoundError: true,
}, },
) )
} }
...@@ -106,6 +108,15 @@ func gormConfig(o *options) *gorm.Config { ...@@ -106,6 +108,15 @@ func gormConfig(o *options) *gorm.Config {
return config return config
} }
func defaultLogger() logger.Interface {
return logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: logger.Warn,
IgnoreRecordNotFoundError: true,
Colorful: true,
})
}
func rwSeparationPlugin(o *options) gorm.Plugin { func rwSeparationPlugin(o *options) gorm.Plugin {
slaves := []gorm.Dialector{} slaves := []gorm.Dialector{}
for _, dsn := range o.slavesDsn { for _, dsn := range o.slavesDsn {
......
...@@ -118,11 +118,11 @@ func CtxTraceIDField(c context.Context) zap.Field { ...@@ -118,11 +118,11 @@ func CtxTraceIDField(c context.Context) zap.Field {
} }
func NewEmptyCtx() context.Context { func NewEmptyCtx() context.Context {
return context.WithValue(context.Background(), ContextTraceIDKey, GenerateTid()) return context.WithValue(context.TODO(), ContextTraceIDKey, GenerateTid())
} }
func NewCtx(ctx context.Context) context.Context { func NewCtx(ctx context.Context) context.Context {
return context.WithValue(context.Background(), ContextTraceIDKey, ctx.Value(ContextTraceIDKey)) return context.WithValue(context.TODO(), ContextTraceIDKey, ctx.Value(ContextTraceIDKey))
} }
func GetCtxString(c context.Context, key string) string { func GetCtxString(c context.Context, key string) string {
......
...@@ -112,7 +112,7 @@ func Retry(retryFunc RetryFunc, opts ...Option) error { ...@@ -112,7 +112,7 @@ func Retry(retryFunc RetryFunc, opts ...Option) error {
select { select {
case <-after: case <-after:
case <-config.context.Done(): case <-config.context.Done():
return errors.New("retry is cancelled") return errors.New("retry is cancelled, because request timeout or cancelled")
} }
} else { } else {
return nil return nil
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论