package logger

import (
	"fmt"
	"io"
	"mini_server/internal/config"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm/logger"
)

var GinLogger io.Writer
var GormLogger logger.Interface

func create_file() *os.File {
	f, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
	if err != nil {
		fmt.Printf("日志文件打开失败，err:%v", err)
		os.Exit(-1)
	}
	return f
}

func Init_log() {

	f := create_file()
	// writer := io.MultiWriter(f, os.Stdout)
	writer := io.MultiWriter(f)

	logrus.SetLevel(config.LogLevel)
	//设置日志格式，使用自定义格式
	logrus.SetFormatter(&MyFormatter{for_server: true})
	// 设置业务日志
	gin.DisableConsoleColor()
	logrus.SetOutput(writer)

	// 设置GIN日志文件
	GinLogger = io.MultiWriter(writer)

	gormLogrus := logrus.New()
	gormLogrus.SetFormatter(&MyFormatter{for_gorm: true})
	gormLogrus.SetOutput(writer)
	// 设置GORM日志文件
	GormLogger = NewGormLogger(
		gormLogrus,
		logger.Config{
			SlowThreshold:             time.Second, // 慢SQL阈值
			LogLevel:                  logger.Info,
			Colorful:                  false, // 禁用彩色打印
			IgnoreRecordNotFoundError: true,  // 不打印未查询到的日志
		},
	)
}
