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

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

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

问题

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

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

import (
	"bytes"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func main() {
	// 创建一个缓冲区
	buf := &bytes.Buffer{}

	// 创建一个 zapcore.Encoder 配置
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

	// 创建一个 zapcore.WriteSyncer,将日志写入缓冲区
	writeSyncer := zapcore.AddSync(buf)

	// 创建一个 zapcore.Core,将日志写入缓冲区
	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		writeSyncer,
		zapcore.DebugLevel,
	)

	// 创建一个 Logger,使用上面创建的 Core
	logger := zap.New(core)

	// 在测试中使用 logger 记录日志
	logger.Info("This is a test log message")

	// 从缓冲区读取日志内容
	actual := buf.String()

	// 打印读取到的日志内容
	fmt.Println(actual)
}

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

英文:

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.

l := logger.New(zap.Config{Level: level, Encoding: "json", OutputPaths: []string{"errors.log"}}).
	With(zap.String("app-env", cfg.APP.Environment), zap.String("app-version", cfg.APP.Version))

//reading logs in different file...
data, _ := os.ReadFile("errors.log")
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)。

以下是一个示例:

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var buff bytes.Buffer
var errorBuff bytes.Buffer
logger := zap.New(
	zapcore.NewCore(zapcore.NewJSONEncoder(
        zapcore.EncoderConfig{}), zapcore.AddSync(&buff),
        zapcore.DPanicLevel
    ),
	zap.ErrorOutput(zapcore.AddSync(&errorBuff)),
)
英文:

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:

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var buff bytes.Buffer
var errorBuff bytes.Buffer
logger := zap.New(
	zapcore.NewCore(zapcore.NewJSONEncoder(
        zapcore.EncoderConfig{}), zapcore.AddSync(&buff),
        zapcore.DPanicLevel
    ),
	zap.ErrorOutput(zapcore.AddSync(&errorBuff)),
)

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:

确定