logger.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package logger
  4. import (
  5. "context"
  6. "fmt"
  7. "git.getensh.com/common/gopkgs/id"
  8. jsoniter "github.com/json-iterator/go"
  9. "go.uber.org/zap"
  10. )
  11. // 替换标准库 encoding/json
  12. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  13. var l *zap.Logger
  14. // New 新建日志器
  15. func New(env, level, filename string, maxSize, maxBackups, maxAge int, stacktrace, global bool) *zap.Logger {
  16. encoding := "json"
  17. development := true
  18. if env == "prod" {
  19. development = false
  20. }
  21. js := fmt.Sprintf(`{
  22. "level": "%s",
  23. "encoding": "%s",
  24. "outputPath": "%s"
  25. }`, level, encoding, filename)
  26. zcfg := zapConfig{}
  27. if err := json.Unmarshal([]byte(js), &zcfg); err != nil {
  28. panic(err)
  29. }
  30. zcfg.Development = development
  31. zcfg.DisableStacktrace = !stacktrace
  32. logger := zcfg.New(maxSize, maxBackups, maxAge)
  33. if global {
  34. l = logger
  35. }
  36. return logger
  37. }
  38. // Error log
  39. func Error(msg string, fields ...zap.Field) {
  40. if l != nil {
  41. l.Error(msg, fields...)
  42. }
  43. }
  44. // Info log
  45. func Info(msg string, fields ...zap.Field) {
  46. if l != nil {
  47. l.Info(msg, fields...)
  48. }
  49. }
  50. // Debug log
  51. func Debug(msg string, fields ...zap.Field) {
  52. if l != nil {
  53. l.Debug(msg, fields...)
  54. }
  55. }
  56. // ErrorWithCtx log
  57. func ErrorWithCtx(ctx context.Context, msg string, fields ...zap.Field) {
  58. if l != nil {
  59. fields = append(fields, zap.String("requestId", id.GetRequestId(ctx)))
  60. l.Error(msg, fields...)
  61. }
  62. }
  63. // InfoWithCtx log
  64. func InfoWithCtx(ctx context.Context, msg string, fields ...zap.Field) {
  65. if l != nil {
  66. fields = append(fields, zap.String("requestId", id.GetRequestId(ctx)))
  67. l.Info(msg, fields...)
  68. }
  69. }
  70. // DebugWithCtx log
  71. func DebugWithCtx(ctx context.Context, msg string, fields ...zap.Field) {
  72. if l != nil {
  73. fields = append(fields, zap.String("requestId", id.GetRequestId(ctx)))
  74. l.Debug(msg, fields...)
  75. }
  76. }