golang-im聊天
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.
 
 
 
 

72 rivejä
1.4 KiB

  1. package logger
  2. import (
  3. "os"
  4. "time"
  5. "go.uber.org/zap"
  6. "go.uber.org/zap/zapcore"
  7. lumberjackv2 "gopkg.in/natefinch/lumberjack.v2"
  8. )
  9. const (
  10. Console = "console"
  11. File = "file"
  12. )
  13. var (
  14. Level = zap.DebugLevel
  15. Target = Console
  16. )
  17. var (
  18. Logger *zap.Logger
  19. Sugar *zap.SugaredLogger
  20. )
  21. func NewEncoderConfig() zapcore.EncoderConfig {
  22. return zapcore.EncoderConfig{
  23. // Keys can be anything except the empty string.
  24. TimeKey: "T",
  25. LevelKey: "L",
  26. NameKey: "N",
  27. CallerKey: "C",
  28. MessageKey: "M",
  29. StacktraceKey: "S",
  30. LineEnding: zapcore.DefaultLineEnding,
  31. EncodeLevel: zapcore.CapitalLevelEncoder,
  32. EncodeTime: TimeEncoder,
  33. EncodeDuration: zapcore.StringDurationEncoder,
  34. EncodeCaller: zapcore.ShortCallerEncoder,
  35. }
  36. }
  37. func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
  38. enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
  39. }
  40. func init() {
  41. w := zapcore.AddSync(&lumberjackv2.Logger{
  42. Filename: "log/im.log",
  43. MaxSize: 1024, // megabytes
  44. MaxBackups: 10,
  45. MaxAge: 7, // days
  46. })
  47. var writeSyncer zapcore.WriteSyncer
  48. if Target == Console {
  49. writeSyncer = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout))
  50. }
  51. if Target == File {
  52. writeSyncer = zapcore.NewMultiWriteSyncer(w)
  53. }
  54. core := zapcore.NewCore(
  55. zapcore.NewConsoleEncoder(NewEncoderConfig()),
  56. writeSyncer,
  57. Level,
  58. )
  59. Logger = zap.New(core, zap.AddCaller())
  60. Sugar = Logger.Sugar()
  61. }