Viktor
Viktor

Reputation: 1692

How to add a hook into a zap logger?

I try to add hook with WithOptions but there was nothing printed for catching some of log events:

    logger.WithOptions(zap.Hooks(func(entry zapcore.Entry) error {
        fmt.Println("test hooks test hooks")
        return nil
    }))

Upvotes: 1

Views: 3888

Answers (1)

wijayaerick
wijayaerick

Reputation: 722

From the documentation:

func (log *Logger) WithOptions(opts ...Option) *Logger

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

Notice that it clones a new logger instead of modifying the logger. So, you should reassign the logger variable (or define a new variable) like this:

logger = logger.WithOptions(zap.Hooks(func(entry zapcore.Entry) error {
    fmt.Println("test hooks test hooks")
    return nil
}))

Upvotes: 6

Related Questions