Skip to content

Go Log Rotation: File Size

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Log Rotation: File Size. We cover key concepts, practical examples, and best practices.

Log file rotation -- Use lumberjack with io.MultiWriter to rotate log files and prevent disk space exhaustion.

The Problem

Without rotation, log files grow indefinitely, consuming disk space and making analysis difficult. lumberjack provides automatic rotation by size or age.

Wrong

f, _ := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE, 0644)
log.SetOutput(f)

Output:

// File grows forever. No rotation.
logFile := &lumberjack.Logger{
    Filename:   "app.log",
    MaxSize:    100, // MB
    MaxBackups: 3,
    MaxAge:     28, // days
}
mw := io.MultiWriter(os.Stdout, logFile)
slog.SetDefault(slog.New(slog.NewTextHandler(mw, nil)))

Output:

// Log rotates at 100MB. 3 backups kept for 28 days.

Prevention

  • Use lumberjack for file rotation
  • Use io.MultiWriter for dual output (stdout + file)
  • Set MaxSize, MaxBackups, MaxAge for rotation policy
  • lumberjack implements io.WriteCloser
  • Combine with zap/zerolog writers for structured logging

Common Mistakes with log rotate

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does lumberjack compress old logs?**

Yes. Set lumberjack.Compress = true for gzip compression.

How to rotate on signal?

Call lumberjack.Rotate() in a SIGHUP handler.

Can I use lumberjack with any logger?

Yes. It implements io.WriteCloser.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro