ETCD后台服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB

3 years ago
  1. package logger
  2. import (
  3. "net/url"
  4. "os"
  5. "runtime"
  6. "strings"
  7. "github.com/shiguanghuxian/etcd-manage/program/common"
  8. "go.uber.org/zap"
  9. "go.uber.org/zap/zapcore"
  10. )
  11. // 日志对象
  12. var (
  13. Log *zap.SugaredLogger
  14. )
  15. // InitLogger 日志初始化,用于记录操作日志
  16. func InitLogger(logPath string, isDebug bool) (*zap.SugaredLogger, error) {
  17. infoLogPath := ""
  18. // errorLogPath := ""
  19. if logPath == "" {
  20. logRoot := common.GetRootDir() + "logs" + string(os.PathSeparator)
  21. if isExt, _ := common.PathExists(logRoot); isExt == false {
  22. os.MkdirAll(logRoot, os.ModePerm)
  23. }
  24. infoLogPath = logRoot + "access.log"
  25. } else {
  26. logPath = strings.TrimRight(logPath, string(os.PathSeparator))
  27. infoLogPath = logPath + string(os.PathSeparator) + "access.log"
  28. }
  29. // 兼容win根完整路径问题
  30. zap.RegisterSink("winfile", func(u *url.URL) (zap.Sink, error) {
  31. return os.OpenFile(u.Path[1:], os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
  32. })
  33. cfg := &zap.Config{
  34. Encoding: "json",
  35. }
  36. cfg.EncoderConfig = zap.NewProductionEncoderConfig()
  37. atom := zap.NewAtomicLevel()
  38. if isDebug == true {
  39. atom.SetLevel(zapcore.DebugLevel)
  40. cfg.OutputPaths = []string{"stdout"}
  41. } else {
  42. atom.SetLevel(zapcore.InfoLevel)
  43. if runtime.GOOS == "windows" {
  44. cfg.OutputPaths = []string{"winfile:///" + infoLogPath}
  45. } else {
  46. cfg.OutputPaths = []string{infoLogPath}
  47. }
  48. }
  49. cfg.Level = atom
  50. logger, err := cfg.Build()
  51. if err != nil {
  52. return nil, err
  53. }
  54. Log = logger.Sugar()
  55. return Log, nil
  56. }