log.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package zaplog
  2. import (
  3. "fmt"
  4. "path"
  5. "runtime"
  6. "strings"
  7. rotatelogs "github.com/lestrrat-go/file-rotatelogs"
  8. "go.uber.org/zap"
  9. "go.uber.org/zap/zapcore"
  10. )
  11. var (
  12. Logger *zap.Logger
  13. logInfoFileName = fmt.Sprintf("./logger/zap-info.log")
  14. logErrFileName = fmt.Sprintf("./logger/zap-err.log")
  15. )
  16. func init() {
  17. encoderConfig := zap.NewDevelopmentEncoderConfig()
  18. // 设置日志时间格式
  19. encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
  20. // 日志encoder 还是json encode,把日志进行格式化json格式的
  21. encoder := zapcore.NewJSONEncoder(encoderConfig)
  22. // topicErrors := zapcore.AddSync(ioutil.Discard) //kafka topic
  23. fileInfoWriteSyncer := getFileLogWriter(logInfoFileName)
  24. fileErrWriteSyncer := getFileLogWriter(logErrFileName)
  25. core := zapcore.NewTee(
  26. // zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel), // 打印到控制台
  27. // zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), topicErrors, zapcore.ErrorLevel), // 打印到kafka 待验证
  28. zapcore.NewCore(encoder, fileInfoWriteSyncer, zapcore.InfoLevel), // 打印到指定的日志文件
  29. zapcore.NewCore(encoder, fileErrWriteSyncer, zapcore.ErrorLevel), // 打印到指定的日志文件
  30. )
  31. Logger = zap.New(core)
  32. }
  33. func getFileLogWriter(logFileName string) zapcore.WriteSyncer {
  34. lumberRotateLogs, err := rotatelogs.New(
  35. strings.Replace(logFileName, ".log", "", -1)+"-%Y%m%d.log",
  36. rotatelogs.WithLinkName(logFileName),
  37. rotatelogs.WithRotationCount(2), // 2天的日志
  38. rotatelogs.WithRotationSize(210000000), // 一个文件200MB
  39. )
  40. if err != nil {
  41. panic(err)
  42. }
  43. return zapcore.AddSync(lumberRotateLogs)
  44. }
  45. func getCallerInfoForLog() (callerFields []zap.Field) {
  46. pc, file, line, ok := runtime.Caller(2)
  47. if !ok {
  48. return
  49. }
  50. funcName := runtime.FuncForPC(pc).Name()
  51. funcName = path.Base(funcName)
  52. callerFields = append(callerFields, zap.String("func", funcName), zap.String("file", file), zap.Int("line", line))
  53. return
  54. }
  55. func Info(message string, fields ...zap.Field) {
  56. callerFields := getCallerInfoForLog()
  57. fields = append(fields, callerFields...)
  58. Logger.Info(message, fields...)
  59. }
  60. func Debug(message string, fields ...zap.Field) {
  61. callerFields := getCallerInfoForLog()
  62. fields = append(fields, callerFields...)
  63. Logger.Debug(message, fields...)
  64. }
  65. func Error(message string, fields ...zap.Field) {
  66. callerFields := getCallerInfoForLog()
  67. fields = append(fields, callerFields...)
  68. Logger.Error(message, fields...)
  69. }