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 ¶
- type ColoredFormatter
- type ConsoleOutput
- type Entry
- type Field
- func Any(key string, value interface{}) Field
- func Bool(key string, value bool) Field
- func Duration(key string, value time.Duration) Field
- func Error(err error) Field
- func Float64(key string, value float64) Field
- func Int(key string, value int) Field
- func Int64(key string, value int64) Field
- func String(key string, value string) Field
- func Time(key string, value time.Time) Field
- type Fields
- type FileOutput
- type Formatter
- type JSONFormatter
- type Level
- type Logger
- func (l *Logger) Debug(msg string, fields ...Field)
- func (l *Logger) Error(msg string, fields ...Field)
- func (l *Logger) Fatal(msg string, fields ...Field)
- func (l *Logger) GetLevel() Level
- func (l *Logger) Info(msg string, fields ...Field)
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) Warn(msg string, fields ...Field)
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithFields(fields Fields) *Logger
- type Option
- type Output
- type RotationConfig
- type TextFormatter
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.
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.
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) 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.
type Level ¶
type Level int
Level represents the severity level of a log entry.
func (Level) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (Level) ShortString ¶
ShortString returns a short string representation of the level.
func (*Level) UnmarshalText ¶
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 ¶
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) WithContext ¶
WithContext returns a new logger with the given context.
func (*Logger) WithFields ¶
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 ¶
WithFields adds default fields to all log entries.
func WithFormatter ¶
WithFormatter sets the formatter.
func WithOutputs ¶
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.