123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package initutils
- import (
- "io"
- "log"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "syscall"
- "time"
- rotatelogs "github.com/lestrrat/go-file-rotatelogs"
- "github.com/sirupsen/logrus"
- "github.com/spf13/viper"
- )
- const panicFile = "./log/panic.log"
- func InitCoreDump() error {
- if runtime.GOOS == "windows" {
- return nil
- }
- log.Println("init panic file in unix mode")
- file, err := os.OpenFile(panicFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
- if err != nil {
- logrus.Error(err)
- return err
- }
- if err = syscall.Dup2(int(file.Fd()), int(os.Stderr.Fd())); err != nil {
- return err
- }
- return nil
- }
- func InitLog() {
- if viper.GetBool("log.logrus_json") {
- logrus.SetFormatter(&logrus.JSONFormatter{})
- }
- // log.logrus_level
- switch viper.GetString("log.logrus_level") {
- case "trace":
- logrus.SetLevel(logrus.TraceLevel)
- case "debug":
- logrus.SetLevel(logrus.DebugLevel)
- case "info":
- logrus.SetLevel(logrus.InfoLevel)
- case "warn":
- logrus.SetLevel(logrus.WarnLevel)
- case "error":
- logrus.SetLevel(logrus.ErrorLevel)
- }
- // log.logrus_file
- logrusFile := viper.GetString("log.logrus_file")
- os.MkdirAll(filepath.Dir(logrusFile), os.ModePerm)
- logWriter, _ := rotatelogs.New(
- // 分割后的文件名称
- logrusFile+".%Y%m%d.log",
- // 生成软链,指向最新日志文件
- rotatelogs.WithLinkName(logrusFile),
- // 设置最大保存时间(7天)
- rotatelogs.WithMaxAge(7*24*time.Hour),
- // 设置日志切割时间间隔(1天)
- rotatelogs.WithRotationTime(24*time.Hour),
- )
- if viper.GetBool("log.logrus_console") {
- logrus.SetOutput(io.MultiWriter(logWriter, os.Stdout))
- } else {
- logrus.SetOutput(logWriter)
- }
- // default
- logrus.SetReportCaller(true)
- }
- func InitConf(configName string) {
- //viper.Set("gormlog", true)
- viper.AddConfigPath("conf")
- viper.AddConfigPath(configName)
- viper.SetConfigName("config")
- viper.SetConfigType("yaml")
- viper.AutomaticEnv()
- viper.SetEnvPrefix("web")
- viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
- // 从环境变量总读取
- viper.ReadInConfig()
- }
|