Skip to content

Why is log.With(fields) slower than log.Info(msg, fields) #1112

Answered by abhinav
dmitriy-dokshin asked this question in Q&A
Discussion options

You must be logged in to vote

Hello! Yes, indeed log.With is eager at serializing because it's meant for loggers that are meant to be

logger2 := logger.With(zap.String("foo", "bar"))
// serializes the field immediately so that
// the following does not pay to serialize that field twice.

logger2.Info("stuff happened")  // includes {"foo": "bar"} in the output
logger2.Info("more stuff happened")  // same

logger.With shares the serialized form of those fields between all uses of the logger.

For fields that are not meant to be re-used across loggers, we recommend this pattern:

logger.Info("stuff happened", zap.String("foo", "bar"))

This will serialize those fields only if that log message is actually posted.

We'll try …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by abhinav
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1065 on June 15, 2022 12:47.