logger.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package wrapper
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "go.uber.org/zap"
  6. "go.uber.org/zap/zapcore"
  7. "os"
  8. "path"
  9. )
  10. var Logger *zap.Logger
  11. func LoggerInit(logLevel string, logPath string, isDebug bool) {
  12. if _, err := os.Open(logPath); err != nil && os.IsNotExist(err) {
  13. p, _ := os.Getwd()
  14. logPath = path.Join(p, logPath)
  15. _, err = os.Create(logPath)
  16. }
  17. var js string
  18. if isDebug {
  19. js = fmt.Sprintf(`{
  20. "level": "%s",
  21. "encoding": "json",
  22. "outputPaths": ["stdout","%s"],
  23. "errorOutputPaths": ["stdout"]
  24. }`, logLevel, logPath)
  25. } else {
  26. js = fmt.Sprintf(`{
  27. "level": "%s",
  28. "encoding": "json",
  29. "outputPaths": ["%s"],
  30. "errorOutputPaths": ["%s"]
  31. }`, logLevel, logPath, logPath)
  32. }
  33. var cfg zap.Config
  34. if err := json.Unmarshal([]byte(js), &cfg); err != nil {
  35. panic(err)
  36. }
  37. cfg.EncoderConfig = zap.NewProductionEncoderConfig()
  38. cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
  39. var err error
  40. Logger, err = cfg.Build()
  41. if err != nil {
  42. Logger.Error("init logger error: ", zap.String("err", err.Error()))
  43. } else {
  44. Logger.Info("log init")
  45. }
  46. }
  47. func InitLogger(logPath string) {
  48. }