initLog.go 1023 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package initialize
  2. import (
  3. "dhcp/global"
  4. "fmt"
  5. "github.com/go-logr/zapr"
  6. "go.uber.org/zap"
  7. "go.uber.org/zap/zapcore"
  8. "os"
  9. "time"
  10. )
  11. // defaultLogger is zap logr implementation.
  12. func InitLogger(level string) {
  13. config := zap.NewProductionConfig()
  14. file := initLogFile()
  15. config.OutputPaths = []string{"stdout", file}
  16. switch level {
  17. case "debug":
  18. config.Level = zap.NewAtomicLevelAt(zapcore.DebugLevel)
  19. default:
  20. config.Level = zap.NewAtomicLevelAt(zapcore.InfoLevel)
  21. }
  22. zapLogger, err := config.Build()
  23. if err != nil {
  24. panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
  25. }
  26. global.Log = zapr.NewLogger(zapLogger)
  27. }
  28. func initLogFile() string {
  29. // 获取当前日期
  30. currentTime := time.Now()
  31. err := os.MkdirAll("log", os.ModePerm)
  32. if err != nil {
  33. panic(err)
  34. }
  35. // 格式化日期作为文件名
  36. filename := "log/app_" + currentTime.Format("2006-01-02") + ".log"
  37. _, err2 := os.Create(filename)
  38. if err2 != nil {
  39. global.Log.Error(err2, "create log file failed")
  40. }
  41. return filename
  42. }