initutils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package initutils
  2. import (
  3. "io"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "syscall"
  10. "time"
  11. rotatelogs "github.com/lestrrat/go-file-rotatelogs"
  12. "github.com/sirupsen/logrus"
  13. "github.com/spf13/viper"
  14. )
  15. const panicFile = "./log/panic.log"
  16. func InitCoreDump() error {
  17. if runtime.GOOS == "windows" {
  18. return nil
  19. }
  20. log.Println("init panic file in unix mode")
  21. file, err := os.OpenFile(panicFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  22. if err != nil {
  23. logrus.Error(err)
  24. return err
  25. }
  26. if err = syscall.Dup2(int(file.Fd()), int(os.Stderr.Fd())); err != nil {
  27. return err
  28. }
  29. return nil
  30. }
  31. func InitLog() {
  32. if viper.GetBool("log.logrus_json") {
  33. logrus.SetFormatter(&logrus.JSONFormatter{})
  34. }
  35. // log.logrus_level
  36. switch viper.GetString("log.logrus_level") {
  37. case "trace":
  38. logrus.SetLevel(logrus.TraceLevel)
  39. case "debug":
  40. logrus.SetLevel(logrus.DebugLevel)
  41. case "info":
  42. logrus.SetLevel(logrus.InfoLevel)
  43. case "warn":
  44. logrus.SetLevel(logrus.WarnLevel)
  45. case "error":
  46. logrus.SetLevel(logrus.ErrorLevel)
  47. }
  48. // log.logrus_file
  49. logrusFile := viper.GetString("log.logrus_file")
  50. os.MkdirAll(filepath.Dir(logrusFile), os.ModePerm)
  51. logWriter, _ := rotatelogs.New(
  52. // 分割后的文件名称
  53. logrusFile+".%Y%m%d.log",
  54. // 生成软链,指向最新日志文件
  55. rotatelogs.WithLinkName(logrusFile),
  56. // 设置最大保存时间(7天)
  57. rotatelogs.WithMaxAge(7*24*time.Hour),
  58. // 设置日志切割时间间隔(1天)
  59. rotatelogs.WithRotationTime(24*time.Hour),
  60. )
  61. if viper.GetBool("log.logrus_console") {
  62. logrus.SetOutput(io.MultiWriter(logWriter, os.Stdout))
  63. } else {
  64. logrus.SetOutput(logWriter)
  65. }
  66. // default
  67. logrus.SetReportCaller(true)
  68. }
  69. func InitConf(configName string) {
  70. //viper.Set("gormlog", true)
  71. viper.AddConfigPath("conf")
  72. viper.AddConfigPath(configName)
  73. viper.SetConfigName("config")
  74. viper.SetConfigType("yaml")
  75. viper.AutomaticEnv()
  76. viper.SetEnvPrefix("web")
  77. viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
  78. // 从环境变量总读取
  79. err := viper.ReadInConfig()
  80. if err != nil {
  81. logrus.Fatal(err)
  82. }
  83. }