本篇文章内容:自定义gorm2中log写入方式,可以将信息打印到控制台或者是调用第三方日志框架写入日志。
2.环境gorm.io/gorm v1.21.8
3.代码type Writer struct{
}
func (w Writer) Printf(format string,args ...interface{}) {
// log.Infof(format, args...)
fmt.Printf(format, args...)
}
func openDB(dsn string) *gorm.DB{
newLogger := logger.New(
Writer{},
logger.Config{
SlowThreshold: 200 * time.Millisecond, // Slow SQL threshold
LogLevel: logger.Info, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
return db
}
4.理解
gorm.io/gorm/logger 包中查看,日志接口,可以自己写自定义logger,但本教程是使用官方默认的logger
// Interface logger interface
type Interface interface {
LogMode(LogLevel) Interface
Info(context.Context, string, ...interface{})
Warn(context.Context, string, ...interface{})
Error(context.Context, string, ...interface{})
Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
}
查看1中的实现类,可以在该包下找到已经实现了的logger
type logger struct {
Writer
Config
infoStr, warnStr, errStr string
traceStr, traceErrStr, traceWarnStr string
}
自定义一个 Writer ,实现接口即可
// Writer log writer interface
type Writer interface {
Printf(string, ...interface{})
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)