Skip to content

Instantly share code, notes, and snippets.

@arindam89
Last active February 1, 2023 04:35
Show Gist options
  • Save arindam89/e20c7a51323733da49c6b795343d68ed to your computer and use it in GitHub Desktop.
Save arindam89/e20c7a51323733da49c6b795343d68ed to your computer and use it in GitHub Desktop.
Zap Log Samplers Example
// Sampled Logs with 10% logging
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func main() {
logger, _ := zap.NewProduction()
sampled := zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewSampler(c, time.Second, 10, 100)
})
logger = logger.WithOptions(sampled)
defer logger.Sync()
logger.Info("Starting the application...")
// rest of your code
}
import (
"context"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"hash/fnv"
"math/rand"
)
func main() {
logger, _ := zap.NewProduction()
sampled := zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewSamplerWithOptions(c, time.Second, 10, 100, func(ctx context.Context) bool {
v := ctx.Value("requestID")
if v == nil {
return rand.Intn(100) < 10
}
h := fnv.New64()
_, _ = h.Write([]byte(v.(string)))
return h.Sum64()%100 < 10
})
})
logger = logger.WithOptions(sampled)
defer logger.Sync()
logger.Info("Starting the application...")
// Example request logging
requestID := "123456"
ctx := context.WithValue(context.Background(), "requestID", requestID)
logger.Info("Handling request", zap.String("requestID", requestID))
// rest of your request handling code
}
/* In this example, we're using the zapcore.NewSamplerWithOptions method which takes a custom function
to determine whether to sample a log entry. The custom function takes the context as a parameter and checks
if there is a request ID present in the context. If it is present, it hashes the request ID and returns whether
it falls in the 10% range (by checking if the result of h.Sum64() % 100 is less than 10).
If there is no request ID, it returns the result of a random number generator that returns a value less than 10 with 10% probability.
This way, logs for the same request will either all be logged or all be dropped. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment