Member-only story
What is the best logger in Go?
5 min readAug 26, 2024
There are many logger implements in Go including built-in log.
Today, we will explore three commonly used loggers in Go projects, as well as the built-in logger.
First, let’s output unstructured logs.
Case 1. unstructured log
Benchmark
The following benchmarking code measures only the performance of writing logs to a buffer. It is designed to check both execution time and memory allocation.
package logger
import (
"bytes"
"github.com/rs/zerolog"
"github.com/sirupsen/logrus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"log"
"testing"
)
func BenchmarkLogPrintf(b *testing.B) {
b.ReportAllocs()
var buf bytes.Buffer
log.SetOutput(&buf)
b.ResetTimer()
for i := 0; i < b.N; i++ {
log.Printf("This is a benchmark log entry number %d", i)
}
}
func BenchmarkLogrus(b *testing.B) {
b.ReportAllocs()
var buf bytes.Buffer
logger := logrus.New()
logger.SetOutput(&buf)
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Printf("This is a benchmark log entry number %d", i)
}
}
func BenchmarkZap(b *testing.B) {
b.ReportAllocs()
var buf bytes.Buffer
encoderConfig := zap.NewProductionEncoderConfig()
core := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(&buf),
zapcore.InfoLevel,
)
logger := zap.New(core)
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Sugar().Infof("This is a benchmark log entry number %d", i)
}
}
func BenchmarkZerolog(b *testing.B) {
b.ReportAllocs()…