Introduction
Logrus is a structured logger for Go that produces both human-readable text and machine-parsable JSON output. It serves as a drop-in replacement for the standard log package while adding structured fields, log levels, and a hook system for routing entries to external services.
What Logrus Does
- Emits structured log entries with arbitrary key-value fields
- Supports seven severity levels from Trace to Fatal
- Provides pluggable formatters including JSON and colored text
- Offers a hook interface for sending entries to Syslog, Logstash, Elasticsearch, or custom backends
- Works as a drop-in replacement for the Go standard library logger
Architecture Overview
Logrus centers on an Entry struct that carries a map of fields plus metadata (timestamp, level, message). Each Logger instance holds a formatter, output writer, and a slice of hooks. When a log method is called, the logger creates an Entry, runs all registered hooks for that level, formats the entry, and writes it to the output. Thread safety is achieved via a mutex on the logger.
Setup & Configuration
- Import with the alias
logto replace the standard logger seamlessly - Set the global level with
log.SetLevel(log.DebugLevel) - Switch to JSON output via
log.SetFormatter(&log.JSONFormatter{}) - Register hooks with
log.AddHook(myHook)for side-channel delivery - Create multiple logger instances with
logrus.New()for isolated configuration
Key Features
- Field-based structured logging with
WithFieldsandWithField - Fatal and Panic levels that call
os.Exit(1)orpanic()after logging - Thread-safe by default with per-logger mutexes
- Caller reporting via
log.SetReportCaller(true)for file and line info - Large ecosystem of third-party hooks and formatters
Comparison with Similar Tools
- Zap — higher throughput with zero-allocation design but less ergonomic API
- Zerolog — even faster zero-allocation logger focused on JSON output
- slog (Go 1.21+) — standard library structured logging, fewer features but no dependency
- Apex/log — similar API with a handler-based architecture instead of hooks
FAQ
Q: Is Logrus still maintained? A: The author considers it feature-complete and in maintenance mode. Security patches and critical fixes are still applied, but new features are unlikely.
Q: How does Logrus compare to slog? A: slog is built into Go 1.21+ and has lower overhead. Logrus offers a richer hook ecosystem and more formatters but adds an external dependency.
Q: Can I use Logrus in performance-critical paths? A: Logrus allocates on each log call. For hot paths, consider Zap or Zerolog which offer zero-allocation modes.
Q: Does Logrus support context-based logging?
A: Yes, use log.WithContext(ctx) to attach a context, and hooks can extract values from it.