Question: Ignoring certain calls to log #1116
-
Greetings. Is there an easy way to make zap ignore calls to log on any level if one of the fields is zap.Error and it's value is from some slice of errors I would like not to output? I want to do it in the logger itself in one place instead of putting something like if isLoggableError(err) { logger.Error(...) } all over my code. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello, yes this is possible, Your Core will have to track fields added with Core.With, Roughly something like: type omitCore struct {
zapcore.Core // wrapped core
}
func (c *omitCore) With(fields []zapcore.Field) zapcore.Core {
// If one of these fields is the one you want to skip messages for,
// return a no-op core so that `logger.With(badField)` does not
// try to serialize this field.
if shouldSkip(fields) {
return zapcore.NewNopCore()
}
// Delegate to the underlying core and re-wrap it.
return &omitCore{Core: c.Core.With(fields)}
}
func (c *omitCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
// Same, except this time we don't call Write on the wrapped core
// if we don't like the fields.
if shouldSkip(fields) {
return nil
}
return c.Core.Write(ent, fields)
} (I want to clarify that I haven't tested the code above Hope this helps! |
Beta Was this translation helpful? Give feedback.
Hello, yes this is possible,
but you'll have to either write a custom Zap core,
or customize the existing core with the WrapCore option.
Your Core will have to track fields added with Core.With,
probably returning a no-op core if one of the fields is the one you want to reject,
and then in Core.Write, inspect the provided fields,
and skip writing to the wrapped core if the fields meet your criteria.
Roughly something like: