Documentation
¶
Overview ¶
Package log implements a simple logging package with a hierarchical logger tree. Each logger can have children, and configuration changes propagate to descendants. The package is thread-safe; all exported methods are safe for concurrent use.
Each logger has an optional topic. The idea is that this is the main distinction between loggers. Think of the topic as subsystem or part of the code.
Please check out the provided examples to get a better understanding.
A log message consists of a timestamp, a log level, an optional topic, an optional code location and the actual message.
The package defines the following log levels: NOTICE (printed always), PANIC (print and exit 1), ERROR, WARN, INFO, DEBUG, DEBG2, DEBG3, DEBG4, DEBG5
The root logger comes with the folowing properties: log level = WARN (a message logged with a higher level will NOT be printed); no topic; the output is sent to os.Stderr; the timeformat is 2006-01-02 15:04:05.000000; code locations are included in DEBUG and above; the location contains the fully qualified file name and multiline mode is turned off.
At the beginning the only existing logger is the root logger. Derived loggers can be created using New(). Options passed to New() allow to configure the child logger.
Another concept is that of the current logger. It is created using the package level New() function or using the SetCurrent() function. The current logger is used by all package level functions.
All properties of a logger except the topic can be changed after creation. A property change is propagated to all derived loggers recursively. So, if you change the log level of the root logger, this change is inherited by all other loggers.
Example (Lazy) ¶
package main
import (
"github.com/tfoertsch123/log"
"math"
"os"
"time"
)
func main() {
// Use SetNow() to generate a fixed timestamp. This is only needed
// to have this pass as a test so that go doc includes the example.
defer func(orig func() time.Time) { log.SetNow(orig) }(log.SetNow(func() time.Time {
return time.Date(2026, 10, 5, 9, 2, 5, 987654321, time.UTC)
}))
log.SetOutput(os.Stdout)
defer log.Root().Close() // reset/close all loggers
complex_work := func() string {
time.Sleep(100 * time.Millisecond)
return "done"
}
ms := time.Millisecond
// The log level is WARN. So, nothing will be printed.
// Yet it still takes time.
now := time.Now()
log.Infof("complex_work: %s", complex_work())
log.Warnf("complex_work took %vms +/- 20ms",
20*math.Round(float64(time.Now().Sub(now))/float64(20*ms)),
)
now = time.Now()
// Now with lazy execution. This should take almost no time
// since complex_work() is not executed.
log.Infol("complex_work: %s", func() interface{} { return complex_work() })
log.Warnf("complex_work with lazy execution took %vms +/- 20ms",
20*math.Round(float64(time.Now().Sub(now))/float64(20*ms)),
)
// Now let's raise the log level and repeat the previous.
// It should take ~100ms
log.SetLevel(log.INFO)
now = time.Now()
log.Infol("complex_work: %s", func() interface{} { return complex_work() })
log.Warnf("complex_work if actually done took %vms +/- 20ms",
20*math.Round(float64(time.Now().Sub(now))/float64(20*ms)),
)
}
Output: 2026-10-05 09:02:05.987654 WARN complex_work took 100ms +/- 20ms 2026-10-05 09:02:05.987654 WARN complex_work with lazy execution took 0ms +/- 20ms 2026-10-05 09:02:05.987654 NOTICE Setting log level from WARN to INFO 2026-10-05 09:02:05.987654 INFO complex_work: done 2026-10-05 09:02:05.987654 WARN complex_work if actually done took 100ms +/- 20ms
Example (Multiline) ¶
package main
import (
"github.com/tfoertsch123/log"
"os"
"time"
)
func main() {
// Use SetNow() to generate a fixed timestamp. This is only needed
// to have this pass as a test so that go doc includes the example.
defer func(orig func() time.Time) { log.SetNow(orig) }(log.SetNow(func() time.Time {
return time.Date(2026, 10, 5, 9, 2, 5, 987654321, time.UTC)
}))
log.SetOutput(os.Stdout)
defer log.Root().Close() // reset/close all loggers
log.Notice("this\nis a\nmultiline\nmessage")
log.NewC(log.WithMultiLine(true))
log.Notice("this\nis a\nmultiline\nmessage")
}
Output: 2026-10-05 09:02 NOTICE this is a multiline message 2026-10-05 09:02 NOTICE this 2026-10-05 09:02 NOTICE is a 2026-10-05 09:02 NOTICE multiline 2026-10-05 09:02 NOTICE message
Index ¶
- Variables
- func Close()
- func Debg2(m string)
- func Debg2f(f string, p ...interface{})
- func Debg2l(f string, p ...interface{})
- func Debg3(m string)
- func Debg3f(f string, p ...interface{})
- func Debg3l(f string, p ...interface{})
- func Debg4(m string)
- func Debg4f(f string, p ...interface{})
- func Debg4l(f string, p ...interface{})
- func Debg5(m string)
- func Debg5f(f string, p ...interface{})
- func Debg5l(f string, p ...interface{})
- func Debug(m string)
- func Debugf(f string, p ...interface{})
- func Debugl(f string, p ...interface{})
- func Error(m string)
- func Errorf(f string, p ...interface{})
- func Errorl(f string, p ...interface{})
- func GetLocDirectories() int
- func GetMultiLine() bool
- func GetOutput() io.Writer
- func GetTimeFmt() string
- func Info(m string)
- func Infof(f string, p ...interface{})
- func Infol(f string, p ...interface{})
- func Log(lvl Level, m string)
- func Logf(lvl Level, f string, p ...interface{})
- func Logl(lvl Level, f string, p ...interface{})
- func Notice(m string)
- func Noticef(f string, p ...interface{})
- func Noticel(f string, p ...interface{})
- func Panic(m string)
- func Panicf(f string, p ...interface{})
- func Panicl(f string, p ...interface{})
- func SetLevel(lvl Level)
- func SetLocDirectories(n int)
- func SetMinLocation(lvl Level)
- func SetMultiLine(ml bool)
- func SetNow(now_f func() time.Time) func() time.Time
- func SetOutput(out io.Writer)
- func SetTimeFmt(f string)
- func Warn(m string)
- func Warnf(f string, p ...interface{})
- func Warnl(f string, p ...interface{})
- type Level
- type LogOpts
- type Logger
- func (l *Logger) Close() *Logger
- func (l *Logger) Debg2(m string)
- func (l *Logger) Debg2f(f string, p ...interface{})
- func (l *Logger) Debg2l(f string, p ...interface{})
- func (l *Logger) Debg3(m string)
- func (l *Logger) Debg3f(f string, p ...interface{})
- func (l *Logger) Debg3l(f string, p ...interface{})
- func (l *Logger) Debg4(m string)
- func (l *Logger) Debg4f(f string, p ...interface{})
- func (l *Logger) Debg4l(f string, p ...interface{})
- func (l *Logger) Debg5(m string)
- func (l *Logger) Debg5f(f string, p ...interface{})
- func (l *Logger) Debg5l(f string, p ...interface{})
- func (l *Logger) Debug(m string)
- func (l *Logger) Debugf(f string, p ...interface{})
- func (l *Logger) Debugl(f string, p ...interface{})
- func (l *Logger) Error(m string)
- func (l *Logger) Errorf(f string, p ...interface{})
- func (l *Logger) Errorl(f string, p ...interface{})
- func (l *Logger) GetLevel() Level
- func (l *Logger) GetLocDirectories() int
- func (l *Logger) GetMinLocation() Level
- func (l *Logger) GetMultiLine() bool
- func (l *Logger) GetOutput() io.Writer
- func (l *Logger) GetTimeFmt() string
- func (l *Logger) Info(m string)
- func (l *Logger) Infof(f string, p ...interface{})
- func (l *Logger) Infol(f string, p ...interface{})
- func (l *Logger) IsClosed() bool
- func (l *Logger) IsCurrent() bool
- func (l *Logger) IsRoot() bool
- func (l *Logger) Kids(recursive bool) []*Logger
- func (l *Logger) Log(lvl Level, m string)
- func (l *Logger) Logf(lvl Level, f string, p ...interface{})
- func (l *Logger) Logl(lvl Level, f string, p ...interface{})
- func (l *Logger) New(_opts ...Opt) *Logger
- func (l *Logger) Notice(m string)
- func (l *Logger) Noticef(f string, p ...interface{})
- func (l *Logger) Noticel(f string, p ...interface{})
- func (l *Logger) Panic(m string)
- func (l *Logger) Panicf(f string, p ...interface{})
- func (l *Logger) Panicl(f string, p ...interface{})
- func (l *Logger) SetCurrent()
- func (l *Logger) SetLevel(lvl Level)
- func (l *Logger) SetLocDirectories(n int)
- func (l *Logger) SetMinLocation(lvl Level)
- func (l *Logger) SetMultiLine(ml bool)
- func (l *Logger) SetOutput(out io.Writer)
- func (l *Logger) SetTimeFmt(f string)
- func (l *Logger) String() string
- func (l *Logger) Warn(m string)
- func (l *Logger) Warnf(f string, p ...interface{})
- func (l *Logger) Warnl(f string, p ...interface{})
- type Opt
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidLevel error = errors.New(`invalid log level`)
ErrInvalidLevel is returned by ParseLevel when the input string does not match any known log level.
Functions ¶
func Debg2f ¶
func Debg2f(f string, p ...interface{})
Debg2f logs a formatted debug message at level 2 using the current logger.
func Debg2l ¶
func Debg2l(f string, p ...interface{})
Debg2l logs a message with late evaluation at debug level 2 using the current logger.
func Debg3f ¶
func Debg3f(f string, p ...interface{})
Debg3f logs a formatted debug message at level 3 using the current logger.
func Debg3l ¶
func Debg3l(f string, p ...interface{})
Debg3l logs a message with late evaluation at debug level 3 using the current logger.
func Debg4f ¶
func Debg4f(f string, p ...interface{})
Debg4f logs a formatted debug message at level 4 using the current logger.
func Debg4l ¶
func Debg4l(f string, p ...interface{})
Debg4l logs a message with late evaluation at debug level 4 using the current logger.
func Debg5f ¶
func Debg5f(f string, p ...interface{})
Debg5f logs a formatted debug message at level 5 using the current logger.
func Debg5l ¶
func Debg5l(f string, p ...interface{})
Debg5l logs a message with late evaluation at debug level 5 using the current logger.
func Debugf ¶
func Debugf(f string, p ...interface{})
Debugf logs a formatted debug message using the current logger.
func Debugl ¶
func Debugl(f string, p ...interface{})
Debugl logs a message with late evaluation at debug level using the current logger.
func Errorf ¶
func Errorf(f string, p ...interface{})
Errorf logs a formatted error message using the current logger.
func Errorl ¶
func Errorl(f string, p ...interface{})
Errorl logs a message with late evaluation at error level using the current logger.
func GetLocDirectories ¶
func GetLocDirectories() int
GetLocDirectories returns the current logger’s directory component count.
func GetMultiLine ¶
func GetMultiLine() bool
GetMultiLine returns true if multiline mode is on for the current logger.
func GetTimeFmt ¶
func GetTimeFmt() string
GetTimeFmt returns the current logger’s time format string.
func Infof ¶
func Infof(f string, p ...interface{})
Infof logs a formatted info message using the current logger.
func Infol ¶
func Infol(f string, p ...interface{})
Infol logs a message with late evaluation at info level using the current logger.
func Noticef ¶
func Noticef(f string, p ...interface{})
Noticef logs a formatted notice message using the current logger.
func Noticel ¶
func Noticel(f string, p ...interface{})
Noticel logs a message with late evaluation at notice level using the current logger.
func Panic ¶
func Panic(m string)
Panic logs a panic message using the current logger and exits with code 1.
func Panicf ¶
func Panicf(f string, p ...interface{})
Panicf logs a formatted panic message using the current logger and exits with code 1.
func Panicl ¶
func Panicl(f string, p ...interface{})
Panicl logs a message with late evaluation at panic level using the current logger and exits with code 1.
func SetLevel ¶
func SetLevel(lvl Level)
SetLevel sets the minimum log level on the current logger and all its descendants.
func SetLocDirectories ¶
func SetLocDirectories(n int)
SetLocDirectories sets the directory component count on the current logger and its descendants.
func SetMinLocation ¶
func SetMinLocation(lvl Level)
SetMinLocation sets the minimum location level on the current logger and its descendants.
func SetMultiLine ¶
func SetMultiLine(ml bool)
SetMultiLine turns multiline mode on or off for the current logger and all its descendants.
func SetNow ¶
SetNow allows to change this package's notion of now. It's intended to be used mainly for testing and debugging purposes. The default value is time.Now.
func SetTimeFmt ¶
func SetTimeFmt(f string)
SetTimeFmt sets the time format string on the current logger and its descendants.
Types ¶
type Level ¶
type Level int8
Level represents a log severity level. Lower values indicate higher severity. The zero value of Level is PANIC. Use ToLevel or ParseLevel to obtain a valid Level.
const ( // NOTICE is a special level that always prints, regardless of the // logger's threshold. It is the only level that can be lower than PANIC. NOTICE Level = iota - 1 // PANIC is the highest severity. Logging at this level will also call // os.Exit(1). PANIC // ERROR indicates an error condition. ERROR // WARN indicates a warning condition. WARN // INFO indicates an informational message. INFO // DEBUG indicates a debug message. DEBUG // DEBG2 is a more verbose debug level. DEBG2 // DEBG3 is an even more verbose debug level. DEBG3 // DEBG4 is a highly verbose debug level. DEBG4 // DEBG5 is the most verbose debug level. DEBG5 )
func GetMinLocation ¶
func GetMinLocation() Level
GetMinLocation returns the current logger’s minimum location level.
func ParseLevel ¶
ParseLevel parses a string into a Level. It accepts case-insensitive names: "notice", "panic", "error", "warn"/"warning", "info", "debug", "debug2"/"debg2", "debug3"/"debg3", "debug4"/"debg4", "debug5"/"debg5", or the numeric strings "0" through "8". Returns ErrInvalidLevel if the string does not match.
type LogOpts ¶
type LogOpts struct {
// contains filtered or unexported fields
}
LogOpts holds optional configuration for creating a new Logger via New.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger represents a node in a hierarchical logger tree.
func L ¶
func L() *Logger
L returns the current package-level logger. The current logger is used by all top-level logging functions (e.g. Log, Debug). It is protected by a global mutex; use this function to obtain a consistent snapshot.
func NewC ¶
New creates and returns a new logger as a child of the current logger and sets it as the new current logger. Shortcut for lg=log.L().New(); lg.SetCurrent()
func NewK ¶
New creates and returns a new logger as a child of the current logger without making it the current logger. Shortcut for log.L().New().
func NewR ¶
New creates and returns a new logger as a child of the root logger without making it the current logger. Shortcut for log.Root().New().
func Root ¶
func Root() *Logger
Root returns a pointer to the global root logger. The root logger cannot be closed and is always available.
func (*Logger) Close ¶
Close closes the logger and all its descendants. After closing, the logger and its subtree are marked as closed and cannot be used. The returned pointer is the previous parent (or nil for the root). Once a logger has been closed, it will not send any messages anymore. The root logger cannot be closed. If closed, it will be reinitialized with the default values.
func (*Logger) GetLocDirectories ¶
GetLocDirectories returns the number of directory components shown in source locations.
func (*Logger) GetMinLocation ¶
GetMinLocation returns the logger’s current minimum location level.
func (*Logger) GetMultiLine ¶
GetMultiLine returns true if multiline mode is on for this logger.
func (*Logger) GetTimeFmt ¶
GetTimeFmt returns the logger’s time format string.
func (*Logger) IsCurrent ¶
IsCurrent reports whether the logger is the current package-level logger.
func (*Logger) Kids ¶
Kids returns a list of this logger’s direct children. If recursive is true, it also includes all descendants (depth-first).
func (*Logger) Log ¶
Log outputs a message at the given level if it meets the logger’s threshold. The output includes a timestamp, level, optional topic, optional source location, and message. In multiline mode, the message is split into lines and each line is prefixed as if it was a log message on its own.
func (*Logger) Logl ¶
Logl outputs a formatted message similar to [Fogf] with late evaluation of arguments. Arguments that are functions of type func() interface{} are called to obtain their value.
func (*Logger) New ¶
New creates a new child logger by copying the current logger’s configuration and applying the given options. The new logger is added to this logger’s children set.
func (*Logger) Panicl ¶
Panicl logs a message with late evaluation at panic level and exits with code 1.
func (*Logger) SetCurrent ¶
func (l *Logger) SetCurrent()
SetCurrent makes this logger the current package-level logger. If l is nil, the root logger becomes current.
func (*Logger) SetLevel ¶
SetLevel sets the minimum log level on the current logger and all its descendants.
func (*Logger) SetLocDirectories ¶
SetLocDirectories sets the number of directory components shown in source locations for this logger and all its descendants.
func (*Logger) SetMinLocation ¶
SetMinLocation sets the minimum log level for printing the caller’s source location on this logger and all its descendants. Levels outside the valid range disable location printing.
func (*Logger) SetMultiLine ¶
SetMultiLine turns multiline mode on or off for this logger and all its descendants.
func (*Logger) SetOutput ¶
SetOutput sets the output writer for this logger and all its descendants.
func (*Logger) SetTimeFmt ¶
SetTimeFmt sets the time format string for this logger and all its descendants.
type Opt ¶
type Opt func(*LogOpts)
Opt is a function type used to apply optional settings to a LogOpts.
func WithLocDirectories ¶
WithLocDirectories returns an Opt that sets the number of directory components to include in the printed source location. Negative values print the full path.
func WithMinLocation ¶
WithMinLocation returns an Opt that sets the minimum log level for printing the caller’s source location. Levels outside [NOTICE+1, DEBG5] disable location printing.
func WithMultiLine ¶
WithTimeFmt returns an Opt that turns on/off multiline mode. In multiline mode, line breaks in the log message are detected and each line is prefixed with the normal line prefix.
func WithOutput ¶
WithOutput returns an Opt that sets the output writer.
func WithTimeFmt ¶
WithTimeFmt returns an Opt that sets the time format string. The string is passed to time.Format in order to format the time stamp.