Documentation
¶
Overview ¶
Package log provides a flexible, feature-rich logging system for Go applications. It offers a comprehensive logging solution with multiple severity levels, customizable outputs, formatting options, and concurrent-safe operations.
Key Features:
Log Levels: Supports hierarchical logging levels:
- Panic: Logs message then panics
- Fatal: Logs message then calls os.Exit(1)
- Error: For error conditions
- Warn: For warning conditions
- Info: For informational messages
- Debug: For debugging information
- Trace: For very detailed debugging
Multiple Output Formats:
- Text format with customizable layouts
- JSON format for structured logging
- Support for ANSI colors in terminal output
- Customizable timestamp formats
Flexible Configuration:
- Multiple simultaneous outputs (file, stdout, custom writers)
- Per-output configuration (levels, format, prefix visibility)
- Custom prefixes for application identification
- Adjustable stack frame skipping for wrapper libraries
Output Formatting Options:
- File paths (full or short)
- Function names and addresses
- Line numbers
- Custom prefix handling
- Timestamp formatting
- Level label formatting
Thread Safety:
- Concurrent-safe logging operations
- Safe for multi-goroutine environments
Basic Usage:
logger := log.New("APP") // create new logger with prefix
logger.Info("Starting application...") // simple logging
logger.Errorf("Failed: %v", err) // formatted logging
logger.Debugln("Debug information") // line logging
Output Configuration:
logger.SetOutputs(
log.Output{
Name: "console",
Writer: os.Stdout,
Levels: level.Info | level.Debug,
WithColor: true,
},
log.Output{
Name: "file",
Writer: fileWriter,
Levels: level.Error | level.Fatal,
TextStyle: false, // JSON output
},
)
Default Output Format:
MY-APP: 2023/06/26 11:42:08 ERROR .../ground/log/main.go main:13 some text ====== =================== ===== ============================== ========= | | | | |__ message | | | |_____________________ location | | |_______________________________________ level | |_____________________________________________________ timestamp |__________________________________________________________________ prefix
Layout Options:
- FullFilePath: Complete path to source file
- ShortFilePath: Abbreviated path with configurable sections
- FuncName: Name of calling function
- FuncAddress: Memory address of calling function
- LineNumber: Source code line number
Level-specific Methods:
Each level (Panic, Fatal, Error, etc.) provides three method variants: - Level(args...): Basic logging with space-separated arguments - Levelf(format, args...): Printf-style formatted logging - Levelln(args...): Line logging with space-separated arguments and newline
Thread Safety:
All logging operations are protected by mutex locks, making the logger safe for concurrent use across multiple goroutines.
Global Logger:
The package provides a default global logger instance accessible through
package-level functions. This instance is initialized during package
initialization and can be used directly:
log.Info("Using global logger")
log.SetPrefix("GLOBAL")
Structured Logging:
The logger can act as a backend for the standard library log/slog via
Logger.Handler, or use NewSlog for a ready *slog.Logger:
slogger := log.NewSlog("APP")
slogger.Info("started", "addr", addr)
Conditional Logging:
Use Enabled to skip preparing expensive arguments for a level that no
output is interested in:
if logger.Enabled(level.Debug) {
logger.Debug(expensiveDump())
}
Performance Considerations:
- Use appropriate log levels to minimize runtime overhead
- Consider using JSON format for structured logging needs
- Disable unused log levels in production
Note on Fatal and Panic:
- Fatal functions call os.Exit(1) after logging
- Panic functions call panic() after logging
- Use these levels appropriately based on recovery needs
Index ¶
- Variables
- func Debug(a ...any)
- func Debugf(format string, a ...any)
- func Debugln(a ...any)
- func DeleteOutputs(names ...string)
- func EditOutputs(outputs ...Output) error
- func Enabled(l level.Level) bool
- func Error(a ...any)
- func Errorf(format string, a ...any)
- func Errorln(a ...any)
- func Fatal(a ...any)
- func Fatalf(format string, a ...any)
- func Fatalln(a ...any)
- func Fdebug(w io.Writer, a ...any)
- func Fdebugf(w io.Writer, format string, a ...any)
- func Fdebugln(w io.Writer, a ...any)
- func Ferror(w io.Writer, a ...any)
- func Ferrorf(w io.Writer, format string, a ...any)
- func Ferrorln(w io.Writer, a ...any)
- func Ffatal(w io.Writer, a ...any)
- func Ffatalf(w io.Writer, format string, a ...any)
- func Ffatalln(w io.Writer, a ...any)
- func Finfo(w io.Writer, a ...any)
- func Finfof(w io.Writer, format string, a ...any)
- func Finfoln(w io.Writer, a ...any)
- func Fpanic(w io.Writer, a ...any)
- func Fpanicf(w io.Writer, format string, a ...any)
- func Fpanicln(w io.Writer, a ...any)
- func Ftrace(w io.Writer, a ...any)
- func Ftracef(w io.Writer, format string, a ...any)
- func Ftraceln(w io.Writer, a ...any)
- func Fwarn(w io.Writer, a ...any)
- func Fwarnf(w io.Writer, format string, a ...any)
- func Fwarnln(w io.Writer, a ...any)
- func Info(a ...any)
- func Infof(format string, a ...any)
- func Infoln(a ...any)
- func InitializeDefaultLogger()
- func NewSlog(prefixes ...string) *slog.Logger
- func Panic(a ...any)
- func Panicf(format string, a ...any)
- func Panicln(a ...any)
- func Prefix() string
- func SetDefault(logger *Logger)
- func SetErrorHandler(handler func(o Output, n int, err error))
- func SetOutputs(outputs ...Output) error
- func SetPrefix(prefix string) string
- func SetSkipStackFrames(skips int)
- func SkipStackFrames() int
- func Trace(a ...any)
- func Tracef(format string, a ...any)
- func Traceln(a ...any)
- func Warn(a ...any)
- func Warnf(format string, a ...any)
- func Warnln(a ...any)
- type Logger
- func (logger *Logger) Copy() *Logger
- func (logger *Logger) Debug(a ...any)
- func (logger *Logger) Debugf(format string, a ...any)
- func (logger *Logger) Debugln(a ...any)
- func (logger *Logger) DeleteOutputs(names ...string)
- func (logger *Logger) EditOutputs(outputs ...Output) error
- func (logger *Logger) Enabled(l level.Level) bool
- func (logger *Logger) Error(a ...any)
- func (logger *Logger) Errorf(f string, a ...any)
- func (logger *Logger) Errorln(a ...any)
- func (logger *Logger) Fatal(a ...any)
- func (logger *Logger) Fatalf(format string, a ...any)
- func (logger *Logger) Fatalln(a ...any)
- func (logger *Logger) Fdebug(w io.Writer, a ...any)
- func (logger *Logger) Fdebugf(w io.Writer, format string, a ...any)
- func (logger *Logger) Fdebugln(w io.Writer, a ...any)
- func (logger *Logger) Ferror(w io.Writer, a ...any)
- func (logger *Logger) Ferrorf(w io.Writer, f string, a ...any)
- func (logger *Logger) Ferrorln(w io.Writer, a ...any)
- func (logger *Logger) Ffatal(w io.Writer, a ...any)
- func (logger *Logger) Ffatalf(w io.Writer, format string, a ...any)
- func (logger *Logger) Ffatalln(w io.Writer, a ...any)
- func (logger *Logger) Finfo(w io.Writer, a ...any)
- func (logger *Logger) Finfof(w io.Writer, format string, a ...any)
- func (logger *Logger) Finfoln(w io.Writer, a ...any)
- func (logger *Logger) Fpanic(w io.Writer, a ...any)
- func (logger *Logger) Fpanicf(w io.Writer, format string, a ...any)
- func (logger *Logger) Fpanicln(w io.Writer, a ...any)
- func (logger *Logger) Ftrace(w io.Writer, a ...any)
- func (logger *Logger) Ftracef(w io.Writer, format string, a ...any)
- func (logger *Logger) Ftraceln(w io.Writer, a ...any)
- func (logger *Logger) Fwarn(w io.Writer, a ...any)
- func (logger *Logger) Fwarnf(w io.Writer, format string, a ...any)
- func (logger *Logger) Fwarnln(w io.Writer, a ...any)
- func (logger *Logger) Handler() slog.Handler
- func (logger *Logger) Info(a ...any)
- func (logger *Logger) Infof(format string, a ...any)
- func (logger *Logger) Infoln(a ...any)
- func (logger *Logger) Outputs(names ...string) []Output
- func (logger *Logger) Panic(a ...any)
- func (logger *Logger) Panicf(format string, a ...any)
- func (logger *Logger) Panicln(a ...any)
- func (logger *Logger) Prefix() string
- func (logger *Logger) SetErrorHandler(handler func(o Output, n int, err error))
- func (logger *Logger) SetOutputs(outputs ...Output) error
- func (logger *Logger) SetPrefix(prefix string) string
- func (logger *Logger) SetSkipStackFrames(skip int) int
- func (logger *Logger) SkipStackFrames() int
- func (logger *Logger) Trace(a ...any)
- func (logger *Logger) Tracef(format string, a ...any)
- func (logger *Logger) Traceln(a ...any)
- func (logger *Logger) Warn(a ...any)
- func (logger *Logger) Warnf(format string, a ...any)
- func (logger *Logger) Warnln(a ...any)
- type Output
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Stdout standard rules for displaying logger information's // messages in the console. Stdout = Output{ Name: "stdout", Writer: os.Stdout, Layouts: layout.Default, Levels: level.Info | level.Debug | level.Trace, Space: outSpace, WithPrefix: outWithPrefix, WithColor: outWithColor, Enabled: outEnabled, TextStyle: outTextStyle, TimestampFormat: outTimestampFormat, LevelFormat: outLevelFormat, } // Stderr standard rules for displaying logger errors // messages in the console. Stderr = Output{ Name: "stderr", Writer: os.Stderr, Layouts: layout.Default, Levels: level.Panic | level.Fatal | level.Error | level.Warn, Space: outSpace, WithPrefix: outWithPrefix, WithColor: outWithColor, Enabled: outEnabled, TextStyle: outTextStyle, TimestampFormat: outTimestampFormat, LevelFormat: outLevelFormat, } // Default is output that processes all types of levels // and outputs the result to stdout. Default = Output{ Name: "default", Writer: os.Stdout, Layouts: layout.Default, Levels: Stdout.Levels | Stderr.Levels, Space: outSpace, WithPrefix: outWithPrefix, WithColor: outWithColor, Enabled: outEnabled, TextStyle: outTextStyle, TimestampFormat: outTimestampFormat, LevelFormat: outLevelFormat, } )
Functions ¶
func Debug ¶
func Debug(a ...any)
Debug creates message with Debug level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
func Debugf ¶
Debugf creates message with Debug level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func Debugln ¶
func Debugln(a ...any)
Debugln creates message with Debug, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func DeleteOutputs ¶
func DeleteOutputs(names ...string)
DeleteOutputs deletes the outputs of the log object.
func EditOutputs ¶
EditOutputs edits the outputs of the log object.
func Enabled ¶
Enabled reports whether at least one enabled output of the default logger would emit a message at level l.
func Error ¶
func Error(a ...any)
Error creates message with Error level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
func Errorf ¶
Errorf creates message with Error level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func Errorln ¶
func Errorln(a ...any)
Errorln creates message with Error, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func Fatal ¶
func Fatal(a ...any)
Fatal creates message with Fatal level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
func Fatalf ¶
Fatalf creates message with Fatal level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func Fatalln ¶
func Fatalln(a ...any)
Fatalln creates message with Fatal, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func Fdebug ¶
Fdebug creates message with Debug level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Fdebugf ¶
Fdebugf creates message with Debug level, according to a format specifier and writes to w.
func Fdebugln ¶
Fdebugln creates message with Debug level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Ferror ¶
Ferror creates message with Error level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Ferrorf ¶
Ferrorf creates message with Error level, according to a format specifier and writes to w.
func Ferrorln ¶
Ferrorln creates message with Error level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Ffatal ¶
Ffatal creates message with Fatal level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Ffatalf ¶
Ffatalf creates message with Fatal level, according to a format specifier and writes to w.
func Ffatalln ¶
Ffatalln creates message with Fatal level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Finfo ¶
Finfo creates message with Info level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Finfof ¶
Finfof creates message with Info level, according to a format specifier and writes to w.
func Finfoln ¶
Finfoln creates message with Info level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Fpanic ¶
Fpanic creates message with Panic level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Fpanicf ¶
Fpanicf creates message with Panic level, according to a format specifier and writes to w.
func Fpanicln ¶
Fpanicln creates message with Panic level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended.
func Ftrace ¶
Ftrace creates message with Trace level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Ftracef ¶
Ftracef creates message with Trace level, according to a format specifier and writes to w.
func Ftraceln ¶
Ftraceln creates message with Trace level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Fwarn ¶
Fwarn creates message with Warn level, using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.
func Fwarnf ¶
Fwarnf creates message with Warn level, according to a format specifier and writes to w.
func Fwarnln ¶
Fwarnln creates message with Warn level, using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
func Info ¶
func Info(a ...any)
Info creates message with Info level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
func Infof ¶
Infof creates message with Info level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func Infoln ¶
func Infoln(a ...any)
Infoln creates message with Info, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func InitializeDefaultLogger ¶
func InitializeDefaultLogger()
InitializeDefaultLogger initializes the default logger instance. The function is called when the module is initialized. Calling the function again has no result.
func NewSlog ¶
NewSlog returns a *slog.Logger backed by a fresh logger whose outputs are the usual Stdout and Stderr. It is a convenience wrapper around New(prefixes...).Handler().
Example ¶
package main
import (
"github.com/goloop/log/v2"
)
func main() {
slogger := log.NewSlog("APP")
slogger.Info("user logged in", "user", "bob", "id", 42)
}
Output:
func Panic ¶
func Panic(a ...any)
Panic creates message with Panic level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func Panicf ¶
Panicf creates message with Panic level, according to a format specifier and writes to log.Writer.
func Panicln ¶
func Panicln(a ...any)
Panicln creates message with Panic, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func SetDefault ¶
func SetDefault(logger *Logger)
SetDefault replaces the package-level default logger used by the package-level logging functions (for example to redirect output in tests or to install a pre-configured logger). A nil logger is ignored. Use Log to read the current default.
func SetErrorHandler ¶
SetErrorHandler sets the write-error handler on the default logger. Passing nil restores the default best-effort behaviour.
func SetOutputs ¶
SetOutputs sets the outputs of the log object.
func SetSkipStackFrames ¶
func SetSkipStackFrames(skips int)
SetSkipStackFrames sets skip stack frames level.
func Trace ¶
func Trace(a ...any)
Trace creates message with Trace level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
func Tracef ¶
Tracef creates message with Trace level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func Traceln ¶
func Traceln(a ...any)
Traceln creates message with Trace, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func Warn ¶
func Warn(a ...any)
Warn creates message with Warn level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.
Types ¶
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is a structure that encapsulates logging functionality. It provides an interface to log messages with varying levels of severity, and can be configured to format and output these messages in different ways.
func New ¶
New returns a new Logger object with optional prefixes for log messages. If one or more prefixes are provided, they will be concatenated with hyphens and prepended to each log message. Leading and trailing whitespace characters are stripped from each prefix before concatenation.
Example usage:
// Create a logger without any prefixes.
logger := log.New()
logger.Info("Hello, World!")
// Create a logger with a single prefix 'MYAPP'.
loggerWithPrefix := log.New("MYAPP")
loggerWithPrefix.Info("Hello, World!")
// Create a logger with multiple prefixes 'MYAPP' and 'PREFIX'.
// The prefixes will be joined as 'MYAPP-PREFIX'.
loggerWithMultiplePrefixes := log.New("MYAPP", "PREFIX")
loggerWithMultiplePrefixes.Info("Hello, World!")
// Create a logger with prefixes containing leading/trailing whitespace.
// The whitespace is removed and prefixes are joined as 'MYAPP-PREFIX'.
loggerWithWhitespace := log.New(" MYAPP ", " PREFIX ")
loggerWithWhitespace.Info("Hello, World!")
Parameters:
prefixes: Optional string values to prepend to each log message.
If multiple prefixes are provided, they will be concatenated
with hyphens.
Returns:
A new Logger instance configured with the provided prefixes.
Example ¶
package main
import (
"github.com/goloop/log/v2"
)
func main() {
logger := log.New("APP")
logger.Info("application started")
logger.Debugf("loaded %d modules", 12)
}
Output:
func (*Logger) Debug ¶
Debug creates message with Debug level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Debugf ¶
Debugf creates message with Debug level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.
func (*Logger) Debugln ¶
Debugln creates message with Debug, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) DeleteOutputs ¶
DeleteOutputs deletes outputs by name.
Example usage:
// Delete the "stdout" output. logger.DeleteOutputs(log.Stdout.Name)
func (*Logger) EditOutputs ¶
EditOutputs updates the list of outputs. If the output with the specified name is not set, the function returns an error.
To edit the output, we must specify its name and only those fields that will be edited. Fields that are not specified will not be changed.
Example usage:
// Set default settings.
logger.SetOutputs(log.Stdout, log.Stderr)
// Change the settings for the "stdout" output.
logger.EditOutputs(log.Output{
Name: log.Stdout.Name,
Levels: log.PanicLevel|log.FatalLevel|log.ErrorLevel,
})
func (*Logger) Enabled ¶
Enabled reports whether at least one enabled output would emit a message at level l. Use it to guard the preparation of expensive log arguments that should be skipped when no output is interested in the level:
if logger.Enabled(level.Debug) {
logger.Debug(expensiveDump())
}
Example ¶
package main
import (
"github.com/goloop/log/v2"
"github.com/goloop/log/v2/level"
)
func main() {
logger := log.New("APP")
if logger.Enabled(level.Debug) {
logger.Debug("debug is enabled for at least one output")
}
}
Output:
func (*Logger) Error ¶
Error creates message with Error level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Errorf ¶
Errorf creates message with Error level, according to a format specifier and writes to log.Writer.
func (*Logger) Errorln ¶
Errorln creates message with Error, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) Fatal ¶
Fatal creates message with Fatal level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Fatalf ¶
Fatalf creates message with Fatal level, according to a format specifier and writes to log.Writer.
func (*Logger) Fatalln ¶
Fatalln creates message with Fatal, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) Fdebug ¶
Fdebug creates message with Debug level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Fdebugf ¶
Fdebugf creates message with Debug level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Fdebugln ¶
Fdebugln creates message with Debug level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Ferror ¶
Ferror creates message with Error level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Ferrorf ¶
Ferrorf creates message with Error level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Ferrorln ¶
Ferrorln creates message with Error level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Ffatal ¶
Ffatal creates message with Fatal level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Ffatalf ¶
Ffatalf creates message with Fatal level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Ffatalln ¶
Ffatalln creates message with Fatal level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Finfo ¶
Finfo creates message with Info level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Finfof ¶
Finfof creates message with Info level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Finfoln ¶
Finfoln creates message with Info level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Fpanic ¶
Fpanic creates message with Panic level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Fpanicf ¶
Fpanicf creates message with Panic level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Fpanicln ¶
Fpanicln creates message with Panic level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Ftrace ¶
Ftrace creates message with Trace level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Ftracef ¶
Ftracef creates message with Trace level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Ftraceln ¶
Ftraceln creates message with Trace level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Fwarn ¶
Fwarn creates message with Warn level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are added between operands when neither is a string.
func (*Logger) Fwarnf ¶
Fwarnf creates message with Warn level, according to a format specifier and writes to the configured outputs and additionally to w.
func (*Logger) Fwarnln ¶
Fwarnln creates message with Warn level, using the default formats for its operands and writes them to the configured outputs and to w. Spaces are always added between operands and a newline is appended.
func (*Logger) Handler ¶
Handler returns a slog.Handler that routes slog records through this logger's configured outputs. The slog level is mapped onto the logger levels (Debug, Info, Warn, Error) and the record attributes are appended to the message as space-separated key=value pairs.
In JSON-style outputs the attributes therefore appear inside the message field rather than as separate JSON keys.
Example ¶
package main
import (
"log/slog"
"github.com/goloop/log/v2"
)
func main() {
logger := log.New("APP")
slogger := slog.New(logger.Handler())
slogger.Warn("disk almost full", "free_mb", 128)
}
Output:
func (*Logger) Info ¶
Info creates message with Info level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Infof ¶
Infof creates message with Info level, according to a format specifier and writes to log.Writer.
func (*Logger) Infoln ¶
Infoln creates message with Info, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) Outputs ¶
Outputs returns a list of outputs.
Example usage:
// Get a list of the current outputs. outputs := logger.Outputs() // Add new output. outputs = append(outputs, log.Stdout) // Set new outputs. logger.SetOutputs(outputs...)
func (*Logger) Panic ¶
Panic creates message with Panic level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Panicf ¶
Panicf creates message with Panic level, according to a format specifier and writes to log.Writer.
func (*Logger) Panicln ¶
Panicln creates message with Panic, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) SetErrorHandler ¶
SetErrorHandler sets a function that is called whenever writing a log message to one of the outputs fails. Passing nil restores the default best-effort behaviour (write errors are ignored). The handler is invoked outside the logger's lock, so it may safely call back into the logger.
func (*Logger) SetOutputs ¶
SetOutputs clears all installed outputs and installs new ones from the list. If new outputs are not specified, the logger will not output information anywhere. We must explicitly specify at least one output, or use the defaults: log.Stdout or/and log.Stderr.
Example usage:
// Show only informational levels.
logger.SetOutputs(log.Stdout)
// Show only error and fatal levels.
logger.SetOutputs(log.Stderr)
// Show all levels.
logger.SetOutputs(log.Stdout, log.Stderr)
// Use custom settings.
// Output to the console is different from output to a file.
f, err := os.OpenFile("e.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer f.Close()
logger.SetOutputs(
log.Output{
Name: "errors",
Writer: f,
Levels: log.PanicLevel|log.FatalLevel|log.ErrorLevel,
Formats: log.ShortPathFormat|log.LineNumberFormat,
WithPrefix: log.Yes,
},
log.Stdout,
log.Stderr,
)
If the specified output has an empty name or writer as nil, the function returns an error. An error is returned if two or more outputs have the same name. If the function returns an error, it doesn't change or clear the previously set values.
Example usage:
// Show only informational levels.
logger.SetOutputs(log.Stdout)
// Try to update with incorrect data.
logger.SetOutputs(log.Output{}) // error: the 0 object has empty name
Example ¶
package main
import (
"os"
"github.com/goloop/log/v2"
"github.com/goloop/log/v2/level"
)
func main() {
logger := log.New("APP")
logger.SetOutputs(log.Output{
Name: "console",
Writer: os.Stdout,
Levels: level.Info | level.Warn | level.Error,
})
logger.Info("configured a single console output")
}
Output:
func (*Logger) SetPrefix ¶
SetPrefix sets the prefix to the logger. The prefix is a special value that is inserted before the log-message. It can be used to identify the application that generates the message, if several different applications output to one output.
func (*Logger) SetSkipStackFrames ¶
SetSkipStackFrames sets the number of stack frames to skip before the program counter stack is collected.
If the specified value is less than zero, the value does not change. If too large a value is specified, the maximum allowable value will be set.
func (*Logger) SkipStackFrames ¶
SkipStackFrames returns the number of stack frames to skip before the program counter stack is collected.
func (*Logger) Trace ¶
Trace creates message with Trace level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
func (*Logger) Tracef ¶
Tracef creates message with Trace level, according to a format specifier and writes to log.Writer.
func (*Logger) Traceln ¶
Traceln creates message with Trace, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.
func (*Logger) Warn ¶
Warn creates message with Warn level, using the default formats for its operands and writes to log.Writer. Spaces are added between operands when neither is a string.
type Output ¶
type Output struct {
// Name is the name of the output. It is used to identify
// the output in the list of outputs.
//
// Mandatory parameter, cannot be empty.
// The name must sound like a variable name in most programming languages:
// it must have special characters, not start with a number, etc.
// But the name can be a reserved word like return, for, if ... any.
// The name can also be expressed as a selector name in CSS,
// for example "some-log-file" (without the leading . or # symbols).
Name string
// Writer is the point where the login data will be output,
// for example os.Stdout or text file descriptor.
//
// Mandatory parameter, cannot be empty.
Writer io.Writer
// Layouts is the flag-holder where flags responsible for
// formatting the log message prefix.
Layouts layout.Layout
// Levels is the flag-holder where flags responsible for
// levels of the logging: Panic, Fatal, Error, Warn, Info etc.
Levels level.Level
// Space is the space between the blocks of the
// output prefix.
Space string
// WithPrefix is the flag that determines whether to show the prefix
// in the log-message. I.e., if the prefix is set for the logger,
// it will be convenient for os.Stdout to display it, since several
// applications can send messages at the same time, but this is
// not necessary for the log file because each application has
// its own log file.
//
// This only works when the prefix is set to the logger.
// By default, the prefix is enabled.
//
// Values are given by numerical marks, where:
// - values less than zero are considered false;
// - values greater than zero are considered true;
// - the value set to 0 is considered the default value
// (or don't change, for edit mode).
//
// We can also use the github.com/goloop/trit package and
// the trit.True or trit.False value.
WithPrefix trit.Trit
// WithColor is the flag that determines whether to use color for the
// log-message. Each message level has its own color. This is handy for
// the console to visually see the problem or debug information.
//
// By default, the color is disabled.
//
// Values are given by numerical marks, where:
// - values less than zero are considered false;
// - values greater than zero are considered true;
// - the value set to 0 is considered the default value
// (or don't change, for edit mode).
//
// We can also use the github.com/goloop/trit package and
// the trit.True or trit.False value.
//
// The color scheme works only for UNIX-like systems.
// The color scheme works for flat format only (i.e. display of log
// messages in the form of text, not as JSON).
WithColor trit.Trit
// Enabled is the flag that determines whether to enable the output.
//
// By default, the new output is enable.
//
// Values are given by numerical marks, where:
// - values less than zero are considered false;
// - values greater than zero are considered true;
// - the value set to 0 is considered the default value
// (or don't change, for edit mode).
//
// We can also use the github.com/goloop/trit package and
// the trit.True or trit.False value.
Enabled trit.Trit
// TextStyle is the flag that determines whether to use text style for
// the log-message. Otherwise, the result will be displayed in JSON style.
//
// By default, the new output has text style.
//
// Values are given by numerical marks, where:
// - values less than zero are considered false;
// - values greater than zero are considered true;
// - the value set to 0 is considered the default value
// (or don't change, for edit mode).
//
// We can also use the github.com/goloop/trit package and
// the trit.True or trit.False value.
TextStyle trit.Trit
// TimestampFormat is the format of the timestamp in the log-message.
// Must be specified in the format of the time.Format() function.
TimestampFormat string
// LevelFormat is the format of the level in the log-message.
// Allows us to add additional information or a label around
// the ID of the level, for example, to display the level in
// square brackets: [LEVEL_NAME] - we need to specify the
// format as "[%s]".
LevelFormat string
// contains filtered or unexported fields
}
Output is the type of the logging output configuration. Specifies the destination where the log and display parameters will be output.