How do I benchmark logging overhead using zap in Go?

When it comes to logging in Go applications, it's essential to understand the overhead that logging can introduce. Zap, a high-performance logging library, is a popular choice for this purpose. In this guide, we will demonstrate how to benchmark logging overhead using Zap in Go.

package main

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

func BenchmarkLogging(b *testing.B) {
    logger, _ := zap.NewProduction()
    defer logger.Sync() // flushes buffer, if any
    
    b.ResetTimer() // Reset timer to avoid setup time
    for i := 0; i < b.N; i++ {
        logger.Info("Logging an entry", zap.Int("iteration", i))
    }
}

func main() {
    // This function is used just for demonstration
    logger, _ := zap.NewProduction()
    defer logger.Sync()
    
    start := time.Now()
    for i := 0; i < 1000; i++ {
        logger.Info("Logging entry", zap.Int("iteration", i))
    }
    elapsed := time.Since(start)
    logger.Info("Logging completed", zap.Duration("elapsed", elapsed))
}