package logger

import (
	"github.com/druidcaesa/gotool"
	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/sirupsen/logrus"
	"iot_manager_service/config"
	"iot_manager_service/util/es"
	"os"
	"path"
	"time"
)

var Logger *logrus.Logger

func InitLog() {
	//logFilePath := config.Instance().Logger.Path
	//logFileName := config.Instance().Logger.Name

	//err := os.MkdirAll(logFilePath, os.ModeDir)
	//if err != nil {
	//	gotool.Logs.ErrorLog().Println(err)
	//	panic(err)
	//}

	// 日志文件
	//fileName := path.Join(logFilePath, logFileName)
	//writer, _ := rotatelogs.New(
	//	fileName+".%Y%m%d.log",
	//	rotatelogs.WithMaxAge(15*24*time.Hour),    // 文件最大保存时间
	//	rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
	//)
	if config.Instance().Logger.Switch == 0 {
		logFilePath := config.Instance().Logger.Path
		logFileName := config.Instance().Logger.Name

		err := os.MkdirAll(logFilePath, os.ModeDir)
		if err != nil {
			gotool.Logs.ErrorLog().Println(err)
			panic(err)
		}

		// 日志文件
		fileName := path.Join(logFilePath, logFileName)
		writer, _ := rotatelogs.New(
			fileName+".%Y%m%d.log",
			rotatelogs.WithMaxAge(15*24*time.Hour),    // 文件最大保存时间
			rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
		)
		// 实例化
		logger := logrus.New()

		logger.SetFormatter(&logrus.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05.000",
		})
		// 设置日志级别
		logger.SetLevel(logrus.DebugLevel)
		logger.SetOutput(writer)
		Logger = logger
	} else {
		es.Es.InitES()
		// 实例化
		logger := logrus.New()

		logger.SetFormatter(&logrus.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05.000",
		})
		// 设置日志级别
		logger.SetLevel(logrus.DebugLevel)
		logger.SetOutput(es.EWriter)
		Logger = logger
	}
}
