logger

package
v1.11.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package logger provides a flexible, structured logging system for Buffalo.

Example (DifferentLevels)
package main

import (
	"os"

	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	log := logger.New(
		logger.WithLevel(logger.DEBUG),
		logger.WithFormatter(logger.NewColoredFormatter()),
		logger.WithOutput(logger.NewConsoleOutput(os.Stdout)),
	)

	log.Debug("Debug message")
	log.Info("Info message")
	log.Warn("Warning message")
	log.Error("Error message")
}
Example (StructuredLogging)
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewJSONFormatter()),
		logger.WithOutput(logger.NewStdoutOutput()),
	)

	log.Info("User action",
		logger.String("action", "login"),
		logger.String("username", "john"),
		logger.String("ip", "192.168.1.1"),
		logger.Int("attempt", 1),
		logger.Bool("success", true),
	)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColoredFormatter

type ColoredFormatter struct {
	// TimestampFormat is the format for timestamps.
	TimestampFormat string
	// DisableTimestamp disables timestamp output.
	DisableTimestamp bool
	// DisableColors disables color output.
	DisableColors bool
	// FullTimestamp enables full timestamp instead of just time.
	FullTimestamp bool
}

ColoredFormatter formats log entries with colors for terminal output.

func NewColoredFormatter

func NewColoredFormatter() *ColoredFormatter

NewColoredFormatter creates a new colored formatter.

func (*ColoredFormatter) Format

func (f *ColoredFormatter) Format(entry *Entry) ([]byte, error)

Format formats the entry with colors.

type ConsoleOutput

type ConsoleOutput struct {
	// contains filtered or unexported fields
}

ConsoleOutput writes logs to a writer (typically os.Stdout or os.Stderr).

func NewConsoleOutput

func NewConsoleOutput(writer io.Writer) *ConsoleOutput

NewConsoleOutput creates a new console output.

func NewStderrOutput

func NewStderrOutput() *ConsoleOutput

NewStderrOutput creates a console output that writes to stderr.

func NewStdoutOutput

func NewStdoutOutput() *ConsoleOutput

NewStdoutOutput creates a console output that writes to stdout.

func (*ConsoleOutput) Close

func (o *ConsoleOutput) Close() error

Close closes the output (no-op for console).

func (*ConsoleOutput) Write

func (o *ConsoleOutput) Write(p []byte) error

Write writes the log entry to the console.

type Entry

type Entry struct {
	Time    time.Time
	Level   Level
	Message string
	Fields  Fields
	Context context.Context
}

Entry represents a single log entry.

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field represents a single log field.

func Any

func Any(key string, value interface{}) Field

Any creates a field with any value.

func Bool

func Bool(key string, value bool) Field

Bool creates a bool field.

func Duration

func Duration(key string, value time.Duration) Field

Duration creates a duration field.

func Error

func Error(err error) Field

Error creates an error field.

func Float64

func Float64(key string, value float64) Field

Float64 creates a float64 field.

func Int

func Int(key string, value int) Field

Int creates an int field.

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field.

func String

func String(key string, value string) Field

String creates a string field.

func Time

func Time(key string, value time.Time) Field

Time creates a time field.

type Fields

type Fields map[string]interface{}

Fields represents structured log fields.

type FileOutput

type FileOutput struct {
	// contains filtered or unexported fields
}

FileOutput writes logs to a file with optional rotation.

Example
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	fileOutput, err := logger.NewFileOutput("logs/app.log")
	if err != nil {
		panic(err)
	}
	defer fileOutput.Close()

	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewTextFormatter()),
		logger.WithOutput(fileOutput),
	)

	log.Info("Logging to file")
}
Example (WithRotation)
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	rotation := &logger.RotationConfig{
		MaxSize:    100, // 100 MB
		MaxAge:     7,   // 7 days
		MaxBackups: 5,   // keep 5 old files
		Daily:      true,
	}

	fileOutput, err := logger.NewFileOutputWithRotation("logs/app.log", rotation)
	if err != nil {
		panic(err)
	}
	defer fileOutput.Close()

	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewJSONFormatter()),
		logger.WithOutput(fileOutput),
	)

	log.Info("Logging with rotation")
}

func NewFileOutput

func NewFileOutput(filename string) (*FileOutput, error)

NewFileOutput creates a new file output.

func NewFileOutputWithRotation

func NewFileOutputWithRotation(filename string, rotation *RotationConfig) (*FileOutput, error)

NewFileOutputWithRotation creates a new file output with rotation.

func (*FileOutput) Close

func (o *FileOutput) Close() error

Close closes the file output.

func (*FileOutput) Write

func (o *FileOutput) Write(p []byte) error

Write writes the log entry to the file.

type Formatter

type Formatter interface {
	// Format formats a log entry into bytes.
	Format(entry *Entry) ([]byte, error)
}

Formatter is the interface for formatting log entries.

type JSONFormatter

type JSONFormatter struct {
	// TimestampFormat is the format for timestamps.
	TimestampFormat string
	// PrettyPrint enables pretty-printed JSON.
	PrettyPrint bool
}

JSONFormatter formats log entries as JSON.

Example
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	log := logger.New(
		logger.WithLevel(logger.DEBUG),
		logger.WithFormatter(logger.NewJSONFormatter()),
		logger.WithOutput(logger.NewStdoutOutput()),
	)

	log.Info("JSON formatted log", logger.String("key", "value"))
}

func NewJSONFormatter

func NewJSONFormatter() *JSONFormatter

NewJSONFormatter creates a new JSON formatter.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)

Format formats the entry as JSON.

type Level

type Level int

Level represents the severity level of a log entry.

const (
	// DEBUG level for detailed debugging information.
	DEBUG Level = iota
	// INFO level for general informational messages.
	INFO
	// WARN level for warning messages.
	WARN
	// ERROR level for error messages.
	ERROR
	// FATAL level for fatal error messages.
	FATAL
)

func ParseLevel

func ParseLevel(s string) Level

ParseLevel parses a string into a Level.

func (Level) MarshalText

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Level) ShortString

func (l Level) ShortString() string

ShortString returns a short string representation of the level.

func (Level) String

func (l Level) String() string

String returns the string representation of the level.

func (*Level) UnmarshalText

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is the main logging interface.

Example (MultipleOutputs)
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	// Log to both console and file
	fileOutput, _ := logger.NewFileOutput("logs/app.log")
	defer fileOutput.Close()

	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewTextFormatter()),
		logger.WithOutputs(
			logger.NewStdoutOutput(),
			fileOutput,
		),
	)

	log.Info("This goes to both console and file")
}

func New

func New(opts ...Option) *Logger

New creates a new Logger with the given options.

Example
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	// Create a logger with INFO level and colored output
	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewColoredFormatter()),
		logger.WithOutput(logger.NewStdoutOutput()),
	)

	log.Info("Application started")
	log.Info("Processing request", logger.String("method", "GET"), logger.String("path", "/api/users"))
}

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...Field)

Debug logs a debug message.

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...Field)

Error logs an error message.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message and exits.

func (*Logger) GetLevel

func (l *Logger) GetLevel() Level

GetLevel returns the current log level.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...Field)

Info logs an info message.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

SetLevel changes the log level.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...Field)

Warn logs a warning message.

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a new logger with the given context.

func (*Logger) WithFields

func (l *Logger) WithFields(fields Fields) *Logger

WithFields returns a new logger with additional fields.

Example
package main

import (
	"github.com/massonsky/buffalo/pkg/logger"
)

func main() {
	log := logger.New(
		logger.WithLevel(logger.INFO),
		logger.WithFormatter(logger.NewTextFormatter()),
		logger.WithOutput(logger.NewStdoutOutput()),
	)

	// Create a child logger with default fields
	requestLogger := log.WithFields(logger.Fields{
		"request_id": "12345",
		"user_id":    "user-1",
	})

	requestLogger.Info("Request received")
	requestLogger.Info("Request processed")
}

type Option

type Option func(*Logger)

Option is a function that configures the logger.

func WithFields

func WithFields(fields Fields) Option

WithFields adds default fields to all log entries.

func WithFormatter

func WithFormatter(formatter Formatter) Option

WithFormatter sets the formatter.

func WithLevel

func WithLevel(level Level) Option

WithLevel sets the log level.

func WithOutput

func WithOutput(output Output) Option

WithOutput adds an output destination.

func WithOutputs

func WithOutputs(outputs ...Output) Option

WithOutputs sets multiple output destinations.

type Output

type Output interface {
	// Write writes the formatted log entry.
	Write(p []byte) error
	// Close closes the output.
	Close() error
}

Output is the interface for log output destinations.

type RotationConfig

type RotationConfig struct {
	// MaxSize is the maximum size in megabytes before rotation.
	MaxSize int
	// MaxAge is the maximum number of days to retain old log files.
	MaxAge int
	// MaxBackups is the maximum number of old log files to retain.
	MaxBackups int
	// Compress determines if rotated files should be compressed.
	Compress bool
	// Daily enables daily rotation.
	Daily bool
}

RotationConfig configures log file rotation.

type TextFormatter

type TextFormatter struct {
	// TimestampFormat is the format for timestamps.
	TimestampFormat string
	// DisableTimestamp disables timestamp output.
	DisableTimestamp bool
	// FullTimestamp enables full timestamp instead of just time.
	FullTimestamp bool
	// FieldsOrder defines the order of fields in output.
	FieldsOrder []string
}

TextFormatter formats log entries as plain text.

func NewTextFormatter

func NewTextFormatter() *TextFormatter

NewTextFormatter creates a new text formatter.

func (*TextFormatter) Format

func (f *TextFormatter) Format(entry *Entry) ([]byte, error)

Format formats the entry as plain text.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL