gogo-zap

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
    }))

Solution

  • 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
    }))