Structured, pluggable logging for Go (golang)
npx @tessl/cli install tessl/golang-github-com-sirupsen--logrus@1.9.0Logrus is a structured logging library for Go that provides a pluggable, extensible logging framework completely API-compatible with Go's standard library logger. It enables structured logging with fields, multiple output formats (JSON and text), configurable log levels, hook mechanisms for extending functionality, and customizable formatters.
go get github.com/sirupsen/logrusimport "github.com/sirupsen/logrus"Aliased import (common pattern):
import log "github.com/sirupsen/logrus"import log "github.com/sirupsen/logrus"
func main() {
// Use package-level logger with structured fields
log.WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
}).Info("A walrus appears")
// Simple logging
log.Info("Simple message")
log.Error("An error occurred")
// With error field
err := errors.New("something went wrong")
log.WithError(err).Error("Failed to process")
}Logrus uses a hierarchical logging architecture:
Create custom logger instances and configure output, formatters, and log levels.
// Create new logger with default settings
func New() *Logger
// Get the standard package-level logger
func StandardLogger() *LoggerThe Logger struct:
type Logger struct {
Out io.Writer // Output destination (default: os.Stderr)
Hooks LevelHooks // Hooks for extending functionality
Formatter Formatter // Log formatter (default: TextFormatter)
ReportCaller bool // Log caller information (default: false)
Level Level // Minimum log level (default: InfoLevel)
ExitFunc exitFunc // Exit function (default: os.Exit)
BufferPool BufferPool // Buffer pool for formatting
}Configuration methods:
func (logger *Logger) SetOutput(output io.Writer)
func (logger *Logger) SetFormatter(formatter Formatter)
func (logger *Logger) SetLevel(level Level)
func (logger *Logger) SetReportCaller(reportCaller bool)
func (logger *Logger) SetBufferPool(pool BufferPool)
func (logger *Logger) SetNoLock()
func (logger *Logger) AddHook(hook Hook)
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks
func (logger *Logger) GetLevel() Level
func (logger *Logger) IsLevelEnabled(level Level) boolPackage-level configuration functions (operate on standard logger):
func SetOutput(out io.Writer)
func SetFormatter(formatter Formatter)
func SetLevel(level Level)
func SetReportCaller(include bool)
func SetBufferPool(bp BufferPool)
func AddHook(hook Hook)
func GetLevel() Level
func IsLevelEnabled(level Level) boolSeven log levels in order of increasing severity.
type Level uint32
const (
PanicLevel Level = iota // Logs then panics
FatalLevel // Logs then calls logger.Exit(1)
ErrorLevel // Error messages
WarnLevel // Warning messages
InfoLevel // Informational messages (default)
DebugLevel // Debug messages
TraceLevel // Finest-grained messages
)Level functions:
func ParseLevel(lvl string) (Level, error)
func (level Level) String() string
func (level Level) MarshalText() ([]byte, error)
func (level *Level) UnmarshalText(text []byte) errorLevel variables:
var AllLevels []Level // Slice containing all log levelsAdd structured context to log entries using fields.
type Fields map[string]interface{}Entry creation (returns *Entry for chaining):
// Logger methods
func (logger *Logger) WithField(key string, value interface{}) *Entry
func (logger *Logger) WithFields(fields Fields) *Entry
func (logger *Logger) WithError(err error) *Entry
func (logger *Logger) WithContext(ctx context.Context) *Entry
func (logger *Logger) WithTime(t time.Time) *Entry
// Package-level functions (operate on standard logger)
func WithField(key string, value interface{}) *Entry
func WithFields(fields Fields) *Entry
func WithError(err error) *Entry
func WithContext(ctx context.Context) *Entry
func WithTime(t time.Time) *EntryThe Entry struct:
type Entry struct {
Logger *Logger
Data Fields // User-set fields
Time time.Time // Entry creation time
Level Level // Log level
Caller *runtime.Frame // Calling method info (if ReportCaller enabled)
Message string // Log message
Buffer *bytes.Buffer // Formatter buffer
Context context.Context // User context
}Entry constructor and methods:
func NewEntry(logger *Logger) *Entry
func (entry *Entry) WithField(key string, value interface{}) *Entry
func (entry *Entry) WithFields(fields Fields) *Entry
func (entry *Entry) WithError(err error) *Entry
func (entry *Entry) WithContext(ctx context.Context) *Entry
func (entry *Entry) WithTime(t time.Time) *Entry
func (entry *Entry) Dup() *EntryEntry variables:
var ErrorKey string // Key used when adding errors with WithError (default: "error")Log messages at specific levels. All methods available on Logger, Entry, and as package-level functions.
Trace level (finest-grained):
func (logger *Logger) Trace(args ...interface{})
func (logger *Logger) Tracef(format string, args ...interface{})
func (logger *Logger) Traceln(args ...interface{})
func (logger *Logger) TraceFn(fn LogFunction)
func (entry *Entry) Trace(args ...interface{})
func (entry *Entry) Tracef(format string, args ...interface{})
func (entry *Entry) Traceln(args ...interface{})
func Trace(args ...interface{})
func Tracef(format string, args ...interface{})
func Traceln(args ...interface{})
func TraceFn(fn LogFunction)Debug level:
func (logger *Logger) Debug(args ...interface{})
func (logger *Logger) Debugf(format string, args ...interface{})
func (logger *Logger) Debugln(args ...interface{})
func (logger *Logger) DebugFn(fn LogFunction)
func (entry *Entry) Debug(args ...interface{})
func (entry *Entry) Debugf(format string, args ...interface{})
func (entry *Entry) Debugln(args ...interface{})
func Debug(args ...interface{})
func Debugf(format string, args ...interface{})
func Debugln(args ...interface{})
func DebugFn(fn LogFunction)Info level (default):
func (logger *Logger) Info(args ...interface{})
func (logger *Logger) Infof(format string, args ...interface{})
func (logger *Logger) Infoln(args ...interface{})
func (logger *Logger) InfoFn(fn LogFunction)
func (entry *Entry) Info(args ...interface{})
func (entry *Entry) Infof(format string, args ...interface{})
func (entry *Entry) Infoln(args ...interface{})
func Info(args ...interface{})
func Infof(format string, args ...interface{})
func Infoln(args ...interface{})
func InfoFn(fn LogFunction)Print methods (alias for Info):
func (logger *Logger) Print(args ...interface{})
func (logger *Logger) Printf(format string, args ...interface{})
func (logger *Logger) Println(args ...interface{})
func (logger *Logger) PrintFn(fn LogFunction)
func (entry *Entry) Print(args ...interface{})
func (entry *Entry) Printf(format string, args ...interface{})
func (entry *Entry) Println(args ...interface{})
func Print(args ...interface{})
func Printf(format string, args ...interface{})
func Println(args ...interface{})
func PrintFn(fn LogFunction)Warn level:
func (logger *Logger) Warn(args ...interface{})
func (logger *Logger) Warnf(format string, args ...interface{})
func (logger *Logger) Warnln(args ...interface{})
func (logger *Logger) WarnFn(fn LogFunction)
func (entry *Entry) Warn(args ...interface{})
func (entry *Entry) Warnf(format string, args ...interface{})
func (entry *Entry) Warnln(args ...interface{})
func Warn(args ...interface{})
func Warnf(format string, args ...interface{})
func Warnln(args ...interface{})
func WarnFn(fn LogFunction)Warning methods (alias for Warn):
func (logger *Logger) Warning(args ...interface{})
func (logger *Logger) Warningf(format string, args ...interface{})
func (logger *Logger) Warningln(args ...interface{})
func (logger *Logger) WarningFn(fn LogFunction)
func (entry *Entry) Warning(args ...interface{})
func (entry *Entry) Warningf(format string, args ...interface{})
func (entry *Entry) Warningln(args ...interface{})
func Warning(args ...interface{})
func Warningf(format string, args ...interface{})
func Warningln(args ...interface{})
func WarningFn(fn LogFunction)Error level:
func (logger *Logger) Error(args ...interface{})
func (logger *Logger) Errorf(format string, args ...interface{})
func (logger *Logger) Errorln(args ...interface{})
func (logger *Logger) ErrorFn(fn LogFunction)
func (entry *Entry) Error(args ...interface{})
func (entry *Entry) Errorf(format string, args ...interface{})
func (entry *Entry) Errorln(args ...interface{})
func Error(args ...interface{})
func Errorf(format string, args ...interface{})
func Errorln(args ...interface{})
func ErrorFn(fn LogFunction)Fatal level (logs then exits with code 1):
func (logger *Logger) Fatal(args ...interface{})
func (logger *Logger) Fatalf(format string, args ...interface{})
func (logger *Logger) Fatalln(args ...interface{})
func (logger *Logger) FatalFn(fn LogFunction)
func (entry *Entry) Fatal(args ...interface{})
func (entry *Entry) Fatalf(format string, args ...interface{})
func (entry *Entry) Fatalln(args ...interface{})
func Fatal(args ...interface{})
func Fatalf(format string, args ...interface{})
func Fatalln(args ...interface{})
func FatalFn(fn LogFunction)Panic level (logs then panics):
func (logger *Logger) Panic(args ...interface{})
func (logger *Logger) Panicf(format string, args ...interface{})
func (logger *Logger) Panicln(args ...interface{})
func (logger *Logger) PanicFn(fn LogFunction)
func (entry *Entry) Panic(args ...interface{})
func (entry *Entry) Panicf(format string, args ...interface{})
func (entry *Entry) Panicln(args ...interface{})
func Panic(args ...interface{})
func Panicf(format string, args ...interface{})
func Panicln(args ...interface{})
func PanicFn(fn LogFunction)Generic logging at any level:
func (logger *Logger) Log(level Level, args ...interface{})
func (logger *Logger) Logf(level Level, format string, args ...interface{})
func (logger *Logger) Logln(level Level, args ...interface{})
func (logger *Logger) LogFn(level Level, fn LogFunction)
func (entry *Entry) Log(level Level, args ...interface{})
func (entry *Entry) Logf(level Level, format string, args ...interface{})
func (entry *Entry) Logln(level Level, args ...interface{})LogFunction type for lazy evaluation:
type LogFunction func() []interface{}Register handlers that run before application exit on Fatal log calls.
func RegisterExitHandler(handler func())
func DeferExitHandler(handler func())
func Exit(code int)
func (logger *Logger) Exit(code int)Get io.Writer interfaces for integration with other logging systems.
func (logger *Logger) Writer() *io.PipeWriter
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
func (entry *Entry) Writer() *io.PipeWriter
func (entry *Entry) WriterLevel(level Level) *io.PipeWriterAdditional Entry methods for inspection and formatting.
func (entry *Entry) String() (string, error)
func (entry *Entry) Bytes() ([]byte, error)
func (entry Entry) HasCaller() boolConstants for default field key names:
const (
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
FieldKeyLogrusError = "logrus_error"
FieldKeyFunc = "func"
FieldKeyFile = "file"
)Customize field key names:
type FieldMap map[fieldKey]stringCustom buffer pool for performance optimization.
type BufferPool interface {
Put(*bytes.Buffer)
Get() *bytes.Buffer
}Control concurrent access to logger.
type MutexWrap struct {
// Has unexported fields
}
func (mw *MutexWrap) Lock()
func (mw *MutexWrap) Unlock()
func (mw *MutexWrap) Disable()Control how log entries are formatted for output. Logrus provides two built-in formatters.
Extend logging functionality by firing custom logic on specific log levels.
Logrus provides several interfaces for compatibility and abstraction.