gorm: 配置日志输出到文件

一,官方文档地址:

https://gorm.io/zh_CN/docs/logger.html

二,代码例子:

1,写日志到文件的函数:

// 日志写入到文件
func LogToFile(filename,msg string) {
	// 输出到文件
	//filename := "logs/" + time.Now().Format("2006-01-02") + ".log"
	file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Println("日志文件的打开错误 :", err)
	}
	defer file.Close()
	if _, err := file.WriteString(msg); err != nil {
		fmt.Println("写入日志文件错误 :", err)
	}
}

2,创建写日志的writer

type Writer struct{}

// 自定义的sql日志输出(到文件)
func (w Writer) Printf(format string, args ...interface{}) {
	msg := fmt.Sprintf(format, args...) + "\n"
	fmt.Println(msg)  // 打印到控制台
	//得到文件名:
	now := time.Now()
	dateStr:=now.Format("2006-01-02")
	filePath := "/data/logs/businesslogs/gorm_"+dateStr+".log"

	// 替换掉彩色打印符号
	msg = strings.ReplaceAll(msg, logger.Reset, "")
	msg = strings.ReplaceAll(msg, logger.Red, "")
	msg = strings.ReplaceAll(msg, logger.Green, "")
	msg = strings.ReplaceAll(msg, logger.Yellow, "")
	msg = strings.ReplaceAll(msg, logger.Blue, "")
	msg = strings.ReplaceAll(msg, logger.Magenta, "")
	msg = strings.ReplaceAll(msg, logger.Cyan, "")
	msg = strings.ReplaceAll(msg, logger.White, "")
	msg = strings.ReplaceAll(msg, logger.BlueBold, "")
	msg = strings.ReplaceAll(msg, logger.MagentaBold, "")
	msg = strings.ReplaceAll(msg, logger.RedBold, "")
	msg = strings.ReplaceAll(msg, logger.YellowBold, "")

	LogToFile(filePath,msg) // 输出到文件
}

3,创建数据库连接对象的配置:

	gormlogger := logger.New(
		Writer{},
		logger.Config{
			//SlowThreshold: time.Second, // 慢 SQL 阈值
			SlowThreshold: 100 * time.Millisecond, // 慢 SQL 阈值
			//LogLevel:    logger.Info, // Log level
			LogLevel:      logger.Warn, // Log level
			Colorful:      true,        // 允许彩色打印
			IgnoreRecordNotFoundError: true,  // Ignore ErrRecordNotFound error for logger
		},
	)
    //标准输出,替换掉
	//DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info),})
	DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: gormlogger,})
	//DBLink.Logger.LogMode(logger.Info)
	if err != nil {
		return err
	}

 

三,测试效果:

/data/site/indu/service/CountryService.go:12 Error 1406 (22001): Data too long for column 'fengturenqing' at row 1
[3.784ms] [rows:0] UPDATE `zr_country` SET ....

 

posted @ 2024-12-07 10:49  刘宏缔的架构森林  阅读(51)  评论(0编辑  收藏  举报