如何使用zap.logger从stdout简单读取(而不创建文件)

huangapple go评论188阅读模式
英文:

How to simply read from stdout with zap.logger (and without creating files)

问题

为了在测试中读取日志而不创建文件,您可以将日志输出到缓冲区(buffer)而不是文件。这样,您可以在测试中直接从缓冲区读取日志内容。

以下是您需要更改的部分:

  1. import (
  2. "bytes"
  3. "os"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. )
  7. func main() {
  8. // 创建一个缓冲区
  9. buf := &bytes.Buffer{}
  10. // 创建一个 zapcore.Encoder 配置
  11. encoderConfig := zap.NewProductionEncoderConfig()
  12. encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
  13. encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
  14. // 创建一个 zapcore.WriteSyncer,将日志写入缓冲区
  15. writeSyncer := zapcore.AddSync(buf)
  16. // 创建一个 zapcore.Core,将日志写入缓冲区
  17. core := zapcore.NewCore(
  18. zapcore.NewConsoleEncoder(encoderConfig),
  19. writeSyncer,
  20. zapcore.DebugLevel,
  21. )
  22. // 创建一个 Logger,使用上面创建的 Core
  23. logger := zap.New(core)
  24. // 在测试中使用 logger 记录日志
  25. logger.Info("This is a test log message")
  26. // 从缓冲区读取日志内容
  27. actual := buf.String()
  28. // 打印读取到的日志内容
  29. fmt.Println(actual)
  30. }

通过上述更改,您将能够在测试中读取日志内容,而无需创建文件。日志将直接写入缓冲区,您可以从缓冲区中获取日志内容进行比较或其他操作。

英文:

For test purposes now I have this configuration of zapLogger with writing to "errors.log".
In test I read the file, compare some needed texts and delete it when test is finished.

  1. l := logger.New(zap.Config{Level: level, Encoding: "json", OutputPaths: []string{"errors.log"}}).
  2. With(zap.String("app-env", cfg.APP.Environment), zap.String("app-version", cfg.APP.Version))
  3. //reading logs in different file...
  4. data, _ := os.ReadFile("errors.log")
  5. actual := string(data)

Is it possible to do that without creating file and reading from the os.Stdout or saving logs to buffer?
I tried several times but with no luck.

What should I change here to be able to read logs in my test without creating a file?

答案1

得分: 2

似乎有一个构造方法 func New(core zapcore.Core, options ...Option)(https://github.com/uber-go/zap/blob/master/logger.go#L67)。
对于 Core,有一个构造方法 func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler)(https://github.com/uber-go/zap/blob/master/zapcore/core.go#L58),其中 ws 指定要写入数据的位置。你可以设置一个 bytes.Buffer 作为这样的 WriteSyncer 并传递它。

请注意,对于发生在日志记录过程中的错误,似乎还需要设置另一个 WriteSyncer。你可以在创建新的日志记录器时传递一个 ErrorOutput 选项(https://github.com/uber-go/zap/blob/master/options.go#L55)。

以下是一个示例:

  1. import (
  2. "go.uber.org/zap"
  3. "go.uber.org/zap/zapcore"
  4. )
  5. var buff bytes.Buffer
  6. var errorBuff bytes.Buffer
  7. logger := zap.New(
  8. zapcore.NewCore(zapcore.NewJSONEncoder(
  9. zapcore.EncoderConfig{}), zapcore.AddSync(&buff),
  10. zapcore.DPanicLevel
  11. ),
  12. zap.ErrorOutput(zapcore.AddSync(&errorBuff)),
  13. )
英文:

Seems like there's a construction method func New(core zapcore.Core, options ...Option) (https://github.com/uber-go/zap/blob/master/logger.go#L67)
For the Core there's a construction method func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) (https://github.com/uber-go/zap/blob/master/zapcore/core.go#L58), with ws specifying where to write the data to. You can just setup a bytes.Buffer as such a WriteSyncer and pass it.

Note that for errors occuring on logging there seems to be another WriteSyncer to be set up. You can pass an ErrorOutput option (https://github.com/uber-go/zap/blob/master/options.go#L55) for then when you create a new logger.

Here's a sketch:

  1. import (
  2. "go.uber.org/zap"
  3. "go.uber.org/zap/zapcore"
  4. )
  5. var buff bytes.Buffer
  6. var errorBuff bytes.Buffer
  7. logger := zap.New(
  8. zapcore.NewCore(zapcore.NewJSONEncoder(
  9. zapcore.EncoderConfig{}), zapcore.AddSync(&buff),
  10. zapcore.DPanicLevel
  11. ),
  12. zap.ErrorOutput(zapcore.AddSync(&errorBuff)),
  13. )

huangapple
  • 本文由 发表于 2022年9月16日 17:36:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73742822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定