log

package
v13.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: Apache-2.0 Imports: 13 Imported by: 14

Documentation

Overview

Package log provides an improved logger

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Enable buffered IO with 1-second flush interval
logger.EnableBufIO(time.Second)

// Set minimal log level
logger.MinLevel(INFO)

// Print message to log
logger.Print(DEBUG, "This is %s message", "debug")

// Package provides different methods for each level
logger.Debug("This is %d %s message", 2, "debug")
logger.Info("This is info message")
logger.Warn("This is warning message")
logger.Error("This is error message")
logger.Crit("This is critical message")

// Enable colors for output
logger.UseColors = true

// Encode messages to JSON
logger.UseJSON = true

// Print caller info
logger.WithCaller = true

// Use custom date & time layout
logger.TimeLayout = time.RFC3339

// Add fields to message
logger.Debug("This is %d %s message", 2, "debug", F{"user", "bob"}, F{"id", 200})

// Or collection of fields. Fields do not require initialization.
var logFields Fields
logFields.Add(F{"user", "bob"}, F{"id", 200})

logger.Debug("This is %d %s message", 2, "debug", logFields)

// AUX message it's unskippable message which will be printed to log file with
// any minimum level
//
// Note that all AUX messages are dropped when using JSON format
logger.Aux("This is aux message")

// Print simple divider
logger.Divider()

// For log rotation we provide method Reopen
logger.Reopen()

// If buffered IO is used, you should flush data before exit
logger.Flush()
Output:

Index

Examples

Constants

View Source
const (
	DEBUG uint8 = 0  // DEBUG debug messages
	INFO  uint8 = 1  // INFO info messages
	WARN  uint8 = 2  // WARN warning messages
	ERROR uint8 = 3  // ERROR error messages
	CRIT  uint8 = 4  // CRIT critical error messages
	AUX   uint8 = 99 // AUX unskipable messages (separators, headers, etc...)
)
View Source
const (
	DATE_LAYOUT_TEXT = "2006/01/02 15:04:05.000" // Datetime layout for text logs
	DATE_LAYOUT_JSON = time.RFC3339              // Datetime layout for JSON logs
)

Variables

View Source
var (
	// ErrNilLogger is returned by Logger struct methods if struct is nil
	ErrNilLogger = errors.New("Logger is nil")

	// ErrUnexpectedLevel is returned by the MinLevel method if given level is unknown
	ErrUnexpectedLevel = errors.New("Unexpected level type")

	// ErrOutputNotSet is returned by the Reopen method if output file is not set
	ErrOutputNotSet = errors.New("Output file is not set")
)

Errors

View Source
var Colors = map[uint8]string{
	DEBUG: "{s-}",
	INFO:  "",
	WARN:  "{y}",
	ERROR: "{#208}",
	CRIT:  "{#196}{*}",
}

Colors colors is map with fmtc color tags for every level

View Source
var Global = &Logger{
	PrefixWarn:  true,
	PrefixError: true,
	PrefixCrit:  true,

	minLevel: INFO,
	mu:       &sync.Mutex{},
}

Global is global logger struct

View Source
var PrefixMap = map[uint8]string{
	DEBUG: "[DEBUG]",
	INFO:  "[INFO]",
	WARN:  "[WARNING]",
	ERROR: "[ERROR]",
	CRIT:  "[CRITICAL]",
}

PrefixMap is map with messages prefixes

Functions

func Aux

func Aux(f string, a ...any) error

Aux writes unskippable message (for separators/headers)

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Aux("Auxiliary message")
Output:

func Crit

func Crit(f string, a ...any) error

Crit writes critical message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Crit("Critical error message")
Output:

func Debug

func Debug(f string, a ...any) error

Debug writes debug message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Debug("Debug message")
Output:

func Divider

func Divider() error

Divider writes simple divider to logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Divider()
Output:

func EnableBufIO

func EnableBufIO(interval time.Duration)

EnableBufIO enables buffered I/O

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Enable buffered IO with 1-second flush interval
EnableBufIO(time.Second)

Info("Info message")

Flush()
Output:

func Error

func Error(f string, a ...any) error

Error writes error message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Error("Error message")
Output:

func Flush

func Flush() error

Flush writes buffered data to file

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Enable buffered IO with 1-second flush interval
EnableBufIO(time.Second)

Info("Info message")

Flush()
Output:

func Info

func Info(f string, a ...any) error

Info writes info message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Info("Info message")
Output:

func Is

func Is(level uint8) bool

Is returns true if current minimal logging level is equal or greater than given

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

if Is(INFO) {
	Info("Info message")
}
Output:

func MinLevel

func MinLevel(level any) error

MinLevel defines minimal logging level

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Set minimal log level to error
MinLevel(ERROR)

Info("This message is not displayed")
Error("This message is displayed")
Output:

func Print

func Print(level uint8, f string, a ...any) error

Print writes message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Print(INFO, "Info message")
Print(ERROR, "Error message")
Output:

func Reopen

func Reopen() error

Reopen close file descriptor for global logger and open it again Useful for log rotation

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// For log rotation we provide method Reopen
Reopen()
Output:

func Set

func Set(file string, perms os.FileMode) error

Set changes global logger output target

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

err = Set("/path/to/file2.log", 0640)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Info("Message will go to file2.log")
Output:

func Warn

func Warn(f string, a ...any) error

Warn writes warning message to global logger output

Example
err := Set("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

Warn("Warning message")
Output:

Types

type F

type F = Field

F is a shortcut for Field struct

type Field

type Field struct {
	Key   string
	Value any
}

Field contains key and value for JSON log

func (Field) String

func (f Field) String() string

String returns string representation of field

type Fields

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

Fields is a field collection

func (*Fields) Add

func (f *Fields) Add(fields ...Field) *Fields

Add adds given fields to collection

Example
// Fields do not require initialization
var f Fields

f.Add(F{"user", "bob"}, F{"id", 200})

Debug("This is %d %s message", 2, "debug", f)
Output:

func (*Fields) Reset

func (f *Fields) Reset() *Fields

Reset removes all fields from collection

Example
// Fields do not require initialization
var f Fields

f.Add(F{"user", "bob"}, F{"id", 200})
Debug("This is %d %s message", 2, "debug", f)

// With Reset you can reuse Fields instance
f.Reset().Add(F{"user", "john"}, F{"id", 201})
Debug("This is %d %s message", 3, "debug", f)
Output:

type ILogger

type ILogger interface {
	Aux(f string, a ...any) error
	Debug(f string, a ...any) error
	Info(f string, a ...any) error
	Warn(f string, a ...any) error
	Error(f string, a ...any) error
	Crit(f string, a ...any) error
	Print(level uint8, f string, a ...any) error
}

ILogger is interface for compatible loggers

type Logger

type Logger struct {
	PrefixDebug bool // Show prefix for debug messages
	PrefixInfo  bool // Show prefix for info messages
	PrefixWarn  bool // Show prefix for warning messages
	PrefixError bool // Show prefix for error messages
	PrefixCrit  bool // Show prefix for critical/fatal messages

	TimeLayout string // Date and time layout used for rendering dates
	UseColors  bool   // Enable ANSI escape codes for colors in output
	UseJSON    bool   // Encode messages to JSON
	WithCaller bool   // Show caller info
	// contains filtered or unexported fields
}

Logger is a basic logger struct

func New

func New(file string, perms os.FileMode) (*Logger, error)

New creates new logger struct

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Package provides different methods for each level
logger.Debug("This is %d %s message", 2, "debug")
logger.Info("This is info message")
logger.Warn("This is warning message")
logger.Error("This is error message")
logger.Crit("This is critical message")

// If buffered IO is used, you should flush data before exit
logger.Flush()
Output:

func (*Logger) Aux

func (l *Logger) Aux(f string, a ...any) error

Aux writes unfiltered message (for separators/headers) to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Aux("Auxiliary message")
Output:

func (*Logger) Crit

func (l *Logger) Crit(f string, a ...any) error

Crit writes critical message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Crit("Critical error message")
Output:

func (*Logger) Debug

func (l *Logger) Debug(f string, a ...any) error

Debug writes debug message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Debug("Debug message")
Output:

func (*Logger) Divider

func (l *Logger) Divider() error

Divider writes simple divider to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Divider()
Output:

func (*Logger) EnableBufIO

func (l *Logger) EnableBufIO(flushInterval time.Duration)

EnableBufIO enables buffered I/O support

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Enable buffered IO with 1-second flush interval
logger.EnableBufIO(time.Second)

logger.Info("Info message")

logger.Flush()
Output:

func (*Logger) Error

func (l *Logger) Error(f string, a ...any) error

Error writes error message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Error("Error message")
Output:

func (*Logger) Flush

func (l *Logger) Flush() error

Flush writes buffered data to file

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Enable buffered IO with 1-second flush interval
logger.EnableBufIO(time.Second)

logger.Info("Info message")

logger.Flush()
Output:

func (*Logger) Info

func (l *Logger) Info(f string, a ...any) error

Info writes info message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Info("Info message")
Output:

func (*Logger) Is

func (l *Logger) Is(level uint8) bool

Is returns true if current minimal logging level is equal or greater than given

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

if logger.Is(INFO) {
	logger.Info("Info message")
}
Output:

func (*Logger) MinLevel

func (l *Logger) MinLevel(level any) error

MinLevel defines minimal logging level

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// Set minimal log level to error
logger.MinLevel(ERROR)

logger.Info("This message is not displayed")
logger.Error("This message is displayed")
Output:

func (*Logger) Print

func (l *Logger) Print(level uint8, f string, a ...any) error

Print writes message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Print(INFO, "Info message")
logger.Print(ERROR, "Error message")
Output:

func (*Logger) Reopen

func (l *Logger) Reopen() error

Reopen closes file descriptor and opens it again Useful for log rotation

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

// For log rotation we provide method Reopen
logger.Reopen()
Output:

func (*Logger) Set

func (l *Logger) Set(file string, perms os.FileMode) error

Set changes logger output target

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

err = logger.Set("/path/to/file2.log", 0640)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Info("Message will go to file2.log")
Output:

func (*Logger) Warn

func (l *Logger) Warn(f string, a ...any) error

Warn writes warning message to logger output

Example
logger, err := New("/path/to/file.log", 0644)

if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

logger.Warn("Warning message")
Output:

type NilLogger

type NilLogger struct{}

NilLogger is Logger (ILogger) compatible logger that doesn't print anything

func (*NilLogger) Aux

func (l *NilLogger) Aux(f string, a ...any) error

Aux do nothing

func (*NilLogger) Crit

func (l *NilLogger) Crit(f string, a ...any) error

Crit do nothing

func (*NilLogger) Debug

func (l *NilLogger) Debug(f string, a ...any) error

Debug do nothing

func (*NilLogger) Error

func (l *NilLogger) Error(f string, a ...any) error

Error do nothing

func (*NilLogger) Info

func (l *NilLogger) Info(f string, a ...any) error

Info do nothing

func (*NilLogger) Print

func (l *NilLogger) Print(level uint8, f string, a ...any) error

Print do nothing

func (*NilLogger) Warn

func (l *NilLogger) Warn(f string, a ...any) error

Warn do nothing

type StdLogger

type StdLogger struct {
	Logger *Logger
}

StdLogger is logger wrapper compatible with stdlib logger

func (*StdLogger) Fatal

func (l *StdLogger) Fatal(v ...any)

Fatal is analog of Fatal from stdlib

func (*StdLogger) Fatalf

func (l *StdLogger) Fatalf(format string, v ...any)

Fatalf is analog of Fatalf from stdlib

func (*StdLogger) Fatalln

func (l *StdLogger) Fatalln(v ...any)

Fatalln is analog of Fatalln from stdlib

func (*StdLogger) Output

func (l *StdLogger) Output(calldepth int, s string) error

Output is analog of Output from stdlib

func (*StdLogger) Panic

func (l *StdLogger) Panic(v ...any)

Panic is analog of Panic from stdlib

func (*StdLogger) Panicf

func (l *StdLogger) Panicf(format string, v ...any)

Panicf is analog of Panicf from stdlib

func (*StdLogger) Panicln

func (l *StdLogger) Panicln(v ...any)

Panicln is analog of Panicln from stdlib

func (*StdLogger) Print

func (l *StdLogger) Print(v ...any)

Print is analog of Print from stdlib

func (*StdLogger) Printf

func (l *StdLogger) Printf(format string, v ...any)

Printf is analog of Printf from stdlib

func (*StdLogger) Println

func (l *StdLogger) Println(v ...any)

Println is analog of Println from stdlib

Jump to

Keyboard shortcuts

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