lgr

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 18 Imported by: 115 modules, 399 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

lgr - simple logger with some extras

Build Status Coverage Status godoc

install

go get github.com/go-pkgz/lgr

usage

    l := lgr.New(lgr.Msec, lgr.Debug, lgr.CallerFile, lgr.CallerFunc) // allow debug and caller info, timestamp with milliseconds
    l.Logf("INFO some important message, %v", err)
    l.Logf("DEBUG some less important message, %v", err)

output looks like this:

2018/01/07 13:02:34.000 INFO  {svc/handler.go:101 h.MyFunc1} some important message, can't open file myfile.xyz
2018/01/07 13:02:34.015 DEBUG {svc/handler.go:155 h.MyFunc2} some less important message, file is too small

Without lgr.Caller* it will drop {caller} part

details

interfaces and default loggers
  • lgr package provides a single interface lgr.L with a single method Logf(format string, args ...interface{}). Function wrapper lgr.Func allows making lgr.L from a function directly.
  • Default logger functionality can be used without lgr.New (see "global logger")
  • Two predefined loggers available: lgr.NoOp (do-nothing logger) and lgr.Std (passing directly to stdlib log)
options

lgr.New call accepts functional options:

  • lgr.Debug - turn debug mode on to allow messages with "DEBUG" level (filtered otherwise)
  • lgr.Trace - turn trace mode on to allow messages with "TRACE" and "DEBUG" levels both (filtered otherwise)
  • lgr.Out(io.Writer) - sets the output writer, default os.Stdout
  • lgr.Err(io.Writer) - sets the error writer, default os.Stderr
  • lgr.CallerFile - adds the caller file info (only affects lgr's native text format, not slog output)
  • lgr.CallerFunc - adds the caller function info (only affects lgr's native text format, not slog output)
  • lgr.CallerPkg - adds the caller package (only affects lgr's native text format, not slog output)
  • lgr.CallerDepth(n) - skips n more stack frames when reporting the caller; use it when lgr is called through a wrapper (1 for lgr.ToWriter, 3 for lgr.ToStdLogger). lgr.SetupStdLogger sets 3 itself, and a lgr.CallerDepth passed to it replaces that value. lgr.ToSlogHandler wrapping a *lgr.Logger takes the caller from the slog record and needs none; a type that embeds *lgr.Logger and logs through its promoted Logf needs 3 when a slog.Logger calls the handler, and a handler or bridge in between adds frames of its own.
  • lgr.LevelBraces - wraps levels with "[" and "]"
  • lgr.Msec - adds milliseconds to timestamp
  • lgr.Format - sets a custom template, overwrites all other formatting modifiers and the mapper set with lgr.Map. A template that fails to parse, or to execute with empty values, is replaced by lgr.Short, and a notice about it is printed to the process stdout, not to the lgr.Out writer.
  • lgr.Secret(secret ...) - sets list of the secrets to hide from the logging outputs, see "secrets".
  • lgr.Map(mapper) - sets mapper functions to change elements of the logging output based on levels.
  • lgr.StackTraceOnError - turns on stack trace for ERROR level. The trace is written to the out writer after the line, not to the err writer.
  • lgr.SlogHandler(h slog.Handler) - delegates logging to the provided slog handler. Of the other options, only these still apply: lgr.Debug and lgr.Trace (lgr filters messages before the handler applies its own level), lgr.Secret for the message, lgr.CallerDepth for the source position passed to the handler, and the exit after FATAL and PANIC, with PANIC also writing *** PANIC: <message> and the goroutine dump to the err writer. All other options are ignored, and ERROR and FATAL lines are not copied to the err writer.

example: l := lgr.New(lgr.Debug, lgr.Msec)

formatting templates:

Several predefined templates provided and can be passed directly to lgr.Format, i.e. lgr.Format(lgr.WithMsec)

	Short      = `{{.DT.Format "2006/01/02 15:04:05"}} {{.Level}} {{.Message}}`
	WithMsec   = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} {{.Message}}`
	WithPkg    = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerPkg}}) {{.Message}}`
	ShortDebug = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFile}}:{{.CallerLine}}) {{.Message}}`
	FuncDebug  = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFunc}}) {{.Message}}`
	FullDebug  = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFile}}:{{.CallerLine}} {{.CallerFunc}}) {{.Message}}`

User can make a custom template and pass it directly to lgr.Format. For example:

    lgr.Format(`{{.Level}} - {{.DT.Format "2006-01-02T15:04:05Z07:00"}} - {{.CallerPkg}} - {{.Message}}`)

Note: formatter (predefined or custom) adds measurable overhead - the cost will depend on the version of Go. You can validate this in your environment via benchmarks: go test -bench=. -run=Bench

secrets

lgr.Secret(secret ...) sets the values to replace with ****** when the logger is created. The list can be changed later, while the logger is in use and other goroutines log:

  • l.AddSecrets(secret ...) and l.RemoveSecrets(secret ...) change the list of a logger made by lgr.New.
  • lgr.AddSecrets(secret ...) and lgr.RemoveSecrets(secret ...) change the package-level list. It is hidden by the global logger and by the std logger set with lgr.SetupStdLogger, in addition to the secrets each of them got with lgr.Secret, and it stays in effect after lgr.Setup, lgr.SetupStdLogger and lgr.SetupWithSlog calls. Loggers made by lgr.New don't use the package-level list.
lgr.Setup(lgr.Secret(dbPassword))
lgr.SetupStdLogger(lgr.Secret(dbPassword))
// later, for example on config reload
lgr.AddSecrets(newToken, newPassword) // hidden in both lgr.Printf and std log.Printf output

Things to know:

  • Empty and whitespace-only values are ignored. Adding a value twice is the same as adding it once, and a single remove drops it.
  • The list of a logger and the package-level list are independent. A value present in both stays hidden until removed from both.
  • A line being logged at the moment of the change may still be written with the previous list.
  • Longer values are replaced first, so a secret containing another secret is hidden as a whole. Secrets that only partially overlap are replaced one after another, and a part of one of them may stay visible.
  • Secrets are hidden in the message passed to the logger. With lgr.ToSlogHandler wrapping a *lgr.Logger, or a type that embeds one, attributes are part of that message, and string values are masked before they are quoted. Any other lgr.L, such as an lgr.Func around a masking logger, gets string values already quoted, so a secret that Go quoting changes, such as one containing a quote, a backslash, a newline or a tab, may not be masked there. lgr.FromSlogHandler adds no masking of its own: the wrapped handler can redact the record itself, for example with ReplaceAttr, or pass it to a masking logger. Attributes added by a slog handler set with lgr.SlogHandler are not processed.
levels

Logf recognizes prefixes like INFO or [INFO] as levels. A bare level counts only when followed by whitespace (space, tab, CR or LF), a colon or the end of the line, so WARNING: disk full is not WARN; a bracketed level may be followed by anything. A line without a recognized prefix is INFO. The full list of supported levels - TRACE, DEBUG, INFO, WARN, ERROR, PANIC and FATAL.

  • TRACE will be filtered unless lgr.Trace option defined
  • DEBUG will be filtered unless lgr.Debug or lgr.Trace options defined
  • INFO and WARN don't have any special behavior attached
  • ERROR sends messages to both out and err writers, once when both are the same file or writer
  • FATAL sends messages to both out and err writers and calls os.Exit(1)
  • PANIC does the same as FATAL but in addition sends dump of callers and runtime info to err.
mapper

Elements of the output can be altered with a set of user defined function passed as lgr.Map options. Such a mapper changes the value of an element (i.e. timestamp, level, message, caller) and has separate functions for each level. Note: both level and messages elements handled by the same function for a given level.

  • MessageFunc maps the message on every level, before the function of the level.
  • TRACE uses DebugFunc, PANIC and FATAL use ErrorFunc.
  • The mapper is ignored when lgr.Format or lgr.SlogHandler is set.
  • A second lgr.Map option replaces the first one.

A typical use-case is to produce colorful output with a user-defined colorization library.

example with fatih/color:

	colorizer := lgr.Mapper{
		ErrorFunc:  func(s string) string { return color.New(color.FgHiRed).Sprint(s) },
		WarnFunc:   func(s string) string { return color.New(color.FgHiYellow).Sprint(s) },
		InfoFunc:   func(s string) string { return color.New(color.FgHiWhite).Sprint(s) },
		DebugFunc:  func(s string) string { return color.New(color.FgWhite).Sprint(s) },
		CallerFunc: func(s string) string { return color.New(color.FgBlue).Sprint(s) },
		TimeFunc:   func(s string) string { return color.New(color.FgCyan).Sprint(s) },
	}

	logOpts := []lgr.Option{lgr.Msec, lgr.LevelBraces, lgr.Map(colorizer)}
adaptors

lgr logger can be converted to io.Writer, *log.Logger, or slog.Handler

  • lgr.ToWriter(l lgr.L, level string) *lgr.Writer - makes io.Writer forwarding write ops to underlying lgr.L
  • lgr.ToStdLogger(l lgr.L, level string) *log.Logger - makes standard logger on top of lgr.L
  • lgr.ToSlogHandler(l lgr.L) slog.Handler - converts lgr.L to a slog.Handler for use with slog. Attributes are written as key=value pairs after the message, with group names joined to the keys by dots, as the slog text handler does. When l is a *lgr.Logger, the Caller* options report the code that called the slog method.

level parameter is optional, if defined (non-empty) will enforce the level.

  • lgr.SetupStdLogger(opts ...Option) initializes std global logger (log.std) with lgr logger and given options. All standard methods like log.Print, log.Println, log.Fatal and so on will be forwarded to lgr. Their lines are leveled by prefix like any other, so log.Fatalf("no prefix") is logged at INFO before the program exits.
  • lgr.SetupWithSlog(logger *slog.Logger) sets up the global logger with a slog logger. It turns on lgr.Debug or lgr.Trace when the handler accepts slog.LevelDebug or slog.LevelDebug-4.
slog integration

In addition to the standard logger interface, lgr provides seamless integration with Go's log/slog package:

Using lgr with slog
// Create lgr logger
lgrLogger := lgr.New(lgr.Debug, lgr.Msec)

// Convert to slog handler and create slog logger
handler := lgr.ToSlogHandler(lgrLogger)
logger := slog.New(handler)

// Use standard slog API with lgr formatting
logger.Info("message", "key1", "value1")
// Output: 2023/09/15 10:34:56.789 INFO  message key1="value1" 
Using slog with lgr interface
// Create slog handler
jsonHandler := slog.NewJSONHandler(os.Stdout, nil)

// Wrap it with lgr interface
logger := lgr.FromSlogHandler(jsonHandler)

// Use lgr API with slog backend
logger.Logf("INFO message with %s", "structured data")
// Output: {"time":"2023-09-15T10:34:56.789Z","level":"INFO","msg":"message with structured data"}

Messages below the handler's level are dropped; with nil options, as above, DEBUG and TRACE are not written. FATAL and PANIC are passed to the handler as ERROR records, and then the program exits with status 1, as it does with lgr.New; a handler that does not accept ERROR drops the record, and the program exits without logging the message. PANIC writes a heading and the stacks of all goroutines to stderr first, leaving the message to the handler. Levels are parsed as described in "levels"; only the space or tab after the level prefix is removed, and the rest of the text reaches the handler as it is, including the newline the standard log package adds when it writes through lgr.ToStdLogger, so a handler that redacts the message sees the whole value. As with lgr.New, Logf called without arguments uses the text as it is, so %% stays %%.

Using slog directly in lgr
// Create a logger that uses slog directly
jsonHandler := slog.NewJSONHandler(os.Stdout, nil)
logger := lgr.New(lgr.SlogHandler(jsonHandler))

// Use lgr API with slog backend
logger.Logf("INFO message")
// Output: {"time":"2023-09-15T10:34:56.789Z","level":"INFO","msg":"message"}

lgr's own level filter runs before the handler: pass lgr.Debug or lgr.Trace to lgr.New as well to let DEBUG or TRACE messages reach it. Then the handler drops the messages below its own level.

JSON output with caller information

To get caller information in JSON output when using slog handlers, create the handler with AddSource: true:

// Create JSON handler with source information (caller info)
jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    AddSource: true,  // This enables caller information in JSON output
})

// Use handler with lgr
logger := lgr.New(lgr.SlogHandler(jsonHandler))

logger.Logf("INFO message with caller info")
// Output will include source file, line and function in JSON

Note: The lgr caller options (lgr.CallerFile, lgr.CallerFunc, lgr.CallerPkg) only work with lgr's native text format and don't affect JSON output from slog handlers. To include caller information in JSON logs:

  1. For slog JSON handlers: Create the handler with AddSource: true as shown above
  2. For text-based logs: Use lgr's native caller options without slog integration

This behavior is designed to respect each logging system's conventions for representing caller information.

global logger

Users should avoid global logger and pass the concrete logger as a dependency. However, in some cases a global logger may be needed, for example migration from stdlib log to lgr. For such cases log "github.com/go-pkgz/lgr" can be imported instead of log package, as long as the code calls only the three functions the global logger provides: Printf, Print, which takes a single string, and Fatalf. For code using the rest of the log API, such as log.Println or log.Fatal, keep the standard log import and call lgr.SetupStdLogger to forward its output to lgr.

Global logger provides lgr.Printf, lgr.Print(line string) and lgr.Fatalf functions. lgr.Fatalf logs a message without a level prefix at FATAL, and exits after any message. User can customize the logger by calling lgr.Setup(options ...). The instance of this logger can be retrieved with lgr.Default()

Documentation

Overview

Package lgr provides a simple logger with some extras. Primary way to log is Logf method. The logger's output can be customized in 2 ways:

  • by setting individual formatting flags, i.e. lgr.New(lgr.Msec, lgr.CallerFunc)
  • by passing formatting template, i.e. lgr.New(lgr.Format(lgr.Short))

Leveled output works for messages based on text prefix, i.e. Logf("INFO some message") means INFO level. Debug and trace levels can be filtered based on lgr.Trace and lgr.Debug options. ERROR, FATAL and PANIC levels send to err as well. FATAL terminate caller application with os.Exit(1) and PANIC also prints stack trace.

Index

Constants

View Source
const (
	// Short logging format
	Short = `{{.DT.Format "2006/01/02 15:04:05"}} {{.Level}} {{.Message}}`
	// WithMsec is a logging format with milliseconds
	WithMsec = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} {{.Message}}`
	// WithPkg is WithMsec logging format with caller package
	WithPkg = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerPkg}}) {{.Message}}`
	// ShortDebug is WithMsec logging format with caller file and line
	ShortDebug = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFile}}:{{.CallerLine}}) {{.Message}}`
	// FuncDebug is WithMsec logging format with caller function
	FuncDebug = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFunc}}) {{.Message}}`
	// FullDebug is WithMsec logging format with caller file, line and function
	FullDebug = `{{.DT.Format "2006/01/02 15:04:05.000"}} {{.Level}} ({{.CallerFile}}:{{.CallerLine}} {{.CallerFunc}}) {{.Message}}`
)

Variables

View Source
var NoOp = Func(func(format string, args ...interface{}) {}) //nolint:revive

NoOp logger

View Source
var Std = Func(func(format string, args ...interface{}) { stdlog.Printf(format, args...) })

Std logger sends to std default logger directly

Functions

func AddSecrets added in v0.13.0

func AddSecrets(vals ...string)

AddSecrets adds values to hide in the output of the default logger and the std logger made by SetupStdLogger. They stay in effect after Setup calls. Loggers made by New are not affected.

func CallerFile added in v0.1.4

func CallerFile(l *Logger)

CallerFile adds caller info with file, and line number. Ignored if Format option used. Note: This option only affects lgr's native text format and is ignored when using SlogHandler.

func CallerFunc added in v0.1.4

func CallerFunc(l *Logger)

CallerFunc adds caller info with function name. Ignored if Format option used. Note: This option only affects lgr's native text format and is ignored when using SlogHandler.

func CallerPkg added in v0.3.0

func CallerPkg(l *Logger)

CallerPkg adds caller's package name. Ignored if Format option used. Note: This option only affects lgr's native text format and is ignored when using SlogHandler.

func Debug

func Debug(l *Logger)

Debug turn on dbg mode

func Fatalf added in v0.2.0

func Fatalf(format string, args ...interface{})

Fatalf logs the message and exits with os.Exit(1). A message without a level prefix is logged at FATAL, so lgr's own output also writes it to the err writer; a message with a prefix is logged at that level.

func LevelBraces added in v0.1.4

func LevelBraces(l *Logger)

LevelBraces surrounds level with [], i.e. [INFO]. Ignored if Format option used.

func Msec added in v0.2.0

func Msec(l *Logger)

Msec adds .msec to timestamp. Ignored if Format option used.

func Print added in v0.1.2

func Print(line string)

Print simplifies replacement of std logger

func Printf

func Printf(format string, args ...interface{})

Printf simplifies replacement of std logger

func RemoveSecrets added in v0.13.0

func RemoveSecrets(vals ...string)

RemoveSecrets stops hiding values added by AddSecrets. A value a logger got with Secret option stays hidden by that logger.

func Setup added in v0.1.1

func Setup(opts ...Option)

Setup default logger with options

func SetupStdLogger added in v0.8.0

func SetupStdLogger(opts ...Option)

SetupStdLogger makes the default std logger with lgr.L

func SetupWithSlog added in v0.12.0

func SetupWithSlog(logger *slog.Logger)

SetupWithSlog sets up the global logger with a slog logger. Debug or Trace is turned on when the handler accepts slog.LevelDebug or slog.LevelDebug-4.

func StackTraceOnError added in v0.10.0

func StackTraceOnError(l *Logger)

StackTraceOnError turns on stack trace for ERROR level.

func ToSlogHandler added in v0.12.0

func ToSlogHandler(l L) slog.Handler

ToSlogHandler converts lgr.L to slog.Handler. Attributes are written as key=value pairs after the message, string values quoted, with group names joined to keys by dots as the slog text handler does. For *Logger and types embedding it, secrets in string values are hidden before quoting. For *Logger, the caller reported by the Caller* options is the one in the slog record, so CallerDepth is not needed.

func ToStdLogger added in v0.5.0

func ToStdLogger(l L, level string) *log.Logger

ToStdLogger makes standard logger

func Trace added in v0.6.0

func Trace(l *Logger)

Trace turn on trace + dbg mode

Types

type Func

type Func func(format string, args ...interface{})

Func type is an adapter to allow the use of ordinary functions as Logger.

func (Func) Logf

func (f Func) Logf(format string, args ...interface{})

Logf calls f(format, args...)

type L

type L interface {
	Logf(format string, args ...interface{})
}

L defines minimal interface used to log things

func Default added in v0.1.1

func Default() L

Default returns pre-constructed def logger (debug off, callers disabled)

func FromSlogHandler added in v0.12.0

func FromSlogHandler(h slog.Handler) L

FromSlogHandler creates lgr.L wrapper around slog.Handler. Records below the level the handler accepts are dropped. FATAL and PANIC are passed as ERROR records and then exit with os.Exit(1), as Logger does; PANIC writes a fixed heading and the stacks of all goroutines to stderr first; the message goes to the handler only.

type Logger

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

Logger provided simple logger with basic support of levels. Thread safe

func New

func New(options ...Option) *Logger

New makes new leveled logger. By default writes to stdout/stderr. default format: 2018/01/07 13:02:34 INFO some message 123

func (*Logger) AddSecrets added in v0.13.0

func (l *Logger) AddSecrets(vals ...string)

AddSecrets adds values to hide in this logger's output. Safe to call while other goroutines log. Empty and whitespace-only values are ignored.

func (*Logger) Logf

func (l *Logger) Logf(format string, args ...interface{})

Logf implements L interface to output with printf style. DEBUG and TRACE filtered out by dbg and trace flags. ERROR, FATAL and PANIC also send the line to err writer, except with SlogHandler, where only PANIC writes its heading and dump there. FATAL and PANIC call os.Exit(1), PANIC dumps all goroutine stacks to err first.

func (*Logger) RemoveSecrets added in v0.13.0

func (l *Logger) RemoveSecrets(vals ...string)

RemoveSecrets stops hiding values in this logger's output, the ones set by Secret option too. Package-level secrets are not affected.

type Mapper added in v0.9.0

type Mapper struct {
	MessageFunc mapFunc // message mapper on all levels, runs before the level's function
	ErrorFunc   mapFunc // level and message mapper on ERROR, PANIC and FATAL levels
	WarnFunc    mapFunc // level and message mapper on WARN level
	InfoFunc    mapFunc // level and message mapper on INFO level
	DebugFunc   mapFunc // level and message mapper on DEBUG and TRACE levels

	CallerFunc mapFunc // caller mapper, all levels
	TimeFunc   mapFunc // time mapper, all levels
}

Mapper defines optional functions to change elements of the logged message for each part, based on levels. Only some mapFunc can be defined, by default does nothing. Can be used to alter the output, for example making some part of the output colorful.

type Option

type Option func(l *Logger)

Option func type

func CallerDepth added in v0.5.0

func CallerDepth(n int) Option

CallerDepth sets number of stack frame skipped for caller reporting, 0 by default

func Err

func Err(w io.Writer) Option

Err sets error writer, stderr by default

func Format added in v0.6.0

func Format(f string) Option

Format sets output layout, overwrites all options for individual parts, i.e. Caller*, Msec, LevelBraces and Map

func Map added in v0.9.0

func Map(m Mapper) Option

Map sets mapper functions to change elements of the logged message based on levels.

func Out

func Out(w io.Writer) Option

Out sets output writer, stdout by default

func Secret added in v0.7.0

func Secret(vals ...string) Option

Secret sets list of substring to be hidden, i.e. replaced by "******" Useful to prevent passwords or other sensitive tokens to be logged. Empty values are ignored. Longer values are replaced first, so a secret containing another one is hidden as a whole.

func SlogHandler added in v0.12.0

func SlogHandler(h slog.Handler) Option

SlogHandler sets slog.Handler to delegate logging to. When using this option, the output format will be controlled by the slog.Handler provided, not by lgr's format options. lgr's Debug and Trace filter runs first, then the handler drops the messages below its own level.

IMPORTANT: When using lgr.SlogHandler:

  1. To get caller information in JSON output, you must create the handler with slog.HandlerOptions{AddSource: true}.

  2. The lgr caller info options (lgr.CallerFile, lgr.CallerFunc) do NOT affect JSON output from slog handlers. They only work with lgr's native text format.

Example of correct setup for JSON with caller info:

// create handler with AddSource enabled
jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    AddSource: true,  // This enables caller information in JSON output
})

// use handler with lgr
logger := lgr.New(lgr.SlogHandler(jsonHandler))

For text format with caller info, use lgr's native caller options:

logger := lgr.New(lgr.CallerFile, lgr.CallerFunc)

type Writer added in v0.5.0

type Writer struct {
	L
	// contains filtered or unexported fields
}

Writer holds lgr.L and wraps with io.Writer interface

func ToWriter added in v0.5.0

func ToWriter(l L, level string) *Writer

ToWriter makes io.Writer for given lgr.L with optional level

func (*Writer) Write added in v0.5.0

func (w *Writer) Write(p []byte) (n int, err error)

Write to lgr.L

Jump to

Keyboard shortcuts

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