log

package module
v2.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 20 Imported by: 0

README

Go Report Card License License Stay with Ukraine

log

log is a leveled, multi-output logging package for Go. A single log call fans out to every configured output, and each output independently decides which levels it accepts, whether it renders text or JSON, whether it uses colour, and how the message prefix is laid out.

It is safe for concurrent use, and work is skipped when nobody needs it: level filtering happens at the source, and stack-frame capture and formatting run only when at least one output requires them, so silent levels stay cheap.

Features

  • Seven levelsPanic, Fatal, Error, Warn, Info, Debug, Trace, each with plain / …f / …ln forms.
  • Multiple outputs — console, files and custom writers at once, each with per-output level filtering, text or JSON, ANSI colour and a configurable prefix layout.
  • Thread-safe — mutex-protected, with buffer pooling on the hot path.
  • slog bridge — back the standard log/slog with NewSlog or logger.Handler().
  • Ad-hoc writers — the F-family also tees a message to a one-off writer.
  • ObservabilityEnabled guards expensive work; SetErrorHandler surfaces failing outputs.

Installation

go get -u github.com/goloop/log/v2
import "github.com/goloop/log/v2"

Requires Go 1.24 or newer.

Quick start

package main

import "github.com/goloop/log/v2"

func main() {
    logger := log.New("APP")

    logger.Info("Application started")
    logger.Infof("User %s logged in", "bob")
    logger.Errorln("Failed to connect to database")
}

Fan out to a coloured console and a JSON file, each filtered by level:

import (
    "github.com/goloop/log/v2"
    "github.com/goloop/log/v2/layout"
    "github.com/goloop/log/v2/level"
)

log.SetOutputs(
    log.Output{
        Name:      "console",
        Writer:    os.Stdout,
        Levels:    level.Info | level.Warn | level.Error,
        Layouts:   layout.Default,
        WithColor: 1,
        TextStyle: 1,
    },
    log.Output{
        Name:      "file",
        Writer:    file,
        Levels:    level.Error | level.Fatal,
        TextStyle: -1, // JSON
    },
)

log.Info("System initialized")
log.Error("Database connection failed")

Back the standard log/slog:

slogger := log.NewSlog("APP")
slogger.Info("user logged in", "user", "bob", "id", 42)

Documentation

Contributing

Contributions are welcome. Please run go test ./..., go vet ./... and gofmt -l . before submitting a pull request.

License

log is released under the MIT License. See LICENSE.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func Debugf(format string, a ...any)

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

func EditOutputs(outputs ...Output) error

EditOutputs edits the outputs of the log object.

func Enabled

func Enabled(l level.Level) bool

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

func Errorf(format string, a ...any)

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

func Fatalf(format string, a ...any)

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

func Fdebug(w io.Writer, a ...any)

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

func Fdebugf(w io.Writer, format string, a ...any)

Fdebugf creates message with Debug level, according to a format specifier and writes to w.

func Fdebugln

func Fdebugln(w io.Writer, a ...any)

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

func Ferror(w io.Writer, a ...any)

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

func Ferrorf(w io.Writer, format string, a ...any)

Ferrorf creates message with Error level, according to a format specifier and writes to w.

func Ferrorln

func Ferrorln(w io.Writer, a ...any)

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

func Ffatal(w io.Writer, a ...any)

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

func Ffatalf(w io.Writer, format string, a ...any)

Ffatalf creates message with Fatal level, according to a format specifier and writes to w.

func Ffatalln

func Ffatalln(w io.Writer, a ...any)

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

func Finfo(w io.Writer, a ...any)

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

func Finfof(w io.Writer, format string, a ...any)

Finfof creates message with Info level, according to a format specifier and writes to w.

func Finfoln

func Finfoln(w io.Writer, a ...any)

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

func Fpanic(w io.Writer, a ...any)

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

func Fpanicf(w io.Writer, format string, a ...any)

Fpanicf creates message with Panic level, according to a format specifier and writes to w.

func Fpanicln

func Fpanicln(w io.Writer, a ...any)

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

func Ftrace(w io.Writer, a ...any)

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

func Ftracef(w io.Writer, format string, a ...any)

Ftracef creates message with Trace level, according to a format specifier and writes to w.

func Ftraceln

func Ftraceln(w io.Writer, a ...any)

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

func Fwarn(w io.Writer, a ...any)

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

func Fwarnf(w io.Writer, format string, a ...any)

Fwarnf creates message with Warn level, according to a format specifier and writes to w.

func Fwarnln

func Fwarnln(w io.Writer, a ...any)

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

func Infof(format string, a ...any)

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

func NewSlog(prefixes ...string) *slog.Logger

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)
}

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

func Panicf(format string, a ...any)

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 Prefix

func Prefix() string

Prefix returns the name of the log object.

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

func SetErrorHandler(handler func(o Output, n int, err error))

SetErrorHandler sets the write-error handler on the default logger. Passing nil restores the default best-effort behaviour.

func SetOutputs

func SetOutputs(outputs ...Output) error

SetOutputs sets the outputs of the log object.

func SetPrefix

func SetPrefix(prefix string) string

SetPrefix sets the name of the logger object.

func SetSkipStackFrames

func SetSkipStackFrames(skips int)

SetSkipStackFrames sets skip stack frames level.

func SkipStackFrames

func SkipStackFrames() int

SkipStackFrames returns 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

func Tracef(format string, a ...any)

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.

func Warnf

func Warnf(format string, a ...any)

Warnf creates message with Warn level, according to a format specifier and writes to log.Writer. It returns the number of bytes written and any write error encountered.

func Warnln

func Warnln(a ...any)

Warnln creates message with Warn, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.

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 Copy

func Copy() *Logger

Copy returns copy of the log object.

func Log

func Log() *Logger

Log returns the default logger instance.

func New

func New(prefixes ...string) *Logger

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)
}

func (*Logger) Copy

func (logger *Logger) Copy() *Logger

Copy returns copy of the logger object.

func (*Logger) Debug

func (logger *Logger) 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.

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, a ...any)

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

func (logger *Logger) 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 (*Logger) DeleteOutputs

func (logger *Logger) DeleteOutputs(names ...string)

DeleteOutputs deletes outputs by name.

Example usage:

// Delete the "stdout" output.
logger.DeleteOutputs(log.Stdout.Name)

func (*Logger) EditOutputs

func (logger *Logger) EditOutputs(outputs ...Output) error

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

func (logger *Logger) Enabled(l level.Level) bool

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")
	}
}

func (*Logger) Error

func (logger *Logger) 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.

func (*Logger) Errorf

func (logger *Logger) Errorf(f string, a ...any)

Errorf creates message with Error level, according to a format specifier and writes to log.Writer.

func (*Logger) Errorln

func (logger *Logger) 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 (*Logger) Fatal

func (logger *Logger) 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.

func (*Logger) Fatalf

func (logger *Logger) Fatalf(format string, a ...any)

Fatalf creates message with Fatal level, according to a format specifier and writes to log.Writer.

func (*Logger) Fatalln

func (logger *Logger) 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 (*Logger) Fdebug

func (logger *Logger) Fdebug(w io.Writer, a ...any)

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

func (logger *Logger) Fdebugf(w io.Writer, format string, a ...any)

Fdebugf creates message with Debug level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Fdebugln

func (logger *Logger) Fdebugln(w io.Writer, a ...any)

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

func (logger *Logger) Ferror(w io.Writer, a ...any)

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

func (logger *Logger) Ferrorf(w io.Writer, f string, a ...any)

Ferrorf creates message with Error level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Ferrorln

func (logger *Logger) Ferrorln(w io.Writer, a ...any)

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

func (logger *Logger) Ffatal(w io.Writer, a ...any)

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

func (logger *Logger) Ffatalf(w io.Writer, format string, a ...any)

Ffatalf creates message with Fatal level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Ffatalln

func (logger *Logger) Ffatalln(w io.Writer, a ...any)

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

func (logger *Logger) Finfo(w io.Writer, a ...any)

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

func (logger *Logger) Finfof(w io.Writer, format string, a ...any)

Finfof creates message with Info level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Finfoln

func (logger *Logger) Finfoln(w io.Writer, a ...any)

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

func (logger *Logger) Fpanic(w io.Writer, a ...any)

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

func (logger *Logger) Fpanicf(w io.Writer, format string, a ...any)

Fpanicf creates message with Panic level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Fpanicln

func (logger *Logger) Fpanicln(w io.Writer, a ...any)

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

func (logger *Logger) Ftrace(w io.Writer, a ...any)

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

func (logger *Logger) Ftracef(w io.Writer, format string, a ...any)

Ftracef creates message with Trace level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Ftraceln

func (logger *Logger) Ftraceln(w io.Writer, a ...any)

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

func (logger *Logger) Fwarn(w io.Writer, a ...any)

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

func (logger *Logger) Fwarnf(w io.Writer, format string, a ...any)

Fwarnf creates message with Warn level, according to a format specifier and writes to the configured outputs and additionally to w.

func (*Logger) Fwarnln

func (logger *Logger) Fwarnln(w io.Writer, a ...any)

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

func (logger *Logger) Handler() slog.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)
}

func (*Logger) Info

func (logger *Logger) 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.

func (*Logger) Infof

func (logger *Logger) Infof(format string, a ...any)

Infof creates message with Info level, according to a format specifier and writes to log.Writer.

func (*Logger) Infoln

func (logger *Logger) 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 (*Logger) Outputs

func (logger *Logger) Outputs(names ...string) []Output

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

func (logger *Logger) 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 (*Logger) Panicf

func (logger *Logger) Panicf(format string, a ...any)

Panicf creates message with Panic level, according to a format specifier and writes to log.Writer.

func (*Logger) Panicln

func (logger *Logger) 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 (*Logger) Prefix

func (logger *Logger) Prefix() string

Prefix returns logger prefix.

func (*Logger) SetErrorHandler

func (logger *Logger) SetErrorHandler(handler func(o Output, n int, err error))

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

func (logger *Logger) SetOutputs(outputs ...Output) error

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")
}

func (*Logger) SetPrefix

func (logger *Logger) SetPrefix(prefix string) string

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

func (logger *Logger) SetSkipStackFrames(skip int) int

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

func (logger *Logger) SkipStackFrames() int

SkipStackFrames returns the number of stack frames to skip before the program counter stack is collected.

func (*Logger) Trace

func (logger *Logger) 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.

func (*Logger) Tracef

func (logger *Logger) Tracef(format string, a ...any)

Tracef creates message with Trace level, according to a format specifier and writes to log.Writer.

func (*Logger) Traceln

func (logger *Logger) 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 (*Logger) Warn

func (logger *Logger) 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.

func (*Logger) Warnf

func (logger *Logger) Warnf(format string, a ...any)

Warnf creates message with Warn level, according to a format specifier and writes to log.Writer.

func (*Logger) Warnln

func (logger *Logger) Warnln(a ...any)

Warnln creates message with Warn, level using the default formats for its operands and writes to log.Writer. Spaces are always added between operands and a newline is appended.

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.

func Outputs

func Outputs(names ...string) []Output

Outputs returns a list of outputs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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