logos

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 27, 2025 License: MIT Imports: 10 Imported by: 0

README

logos


λόγος (logos)

Meaning "word," "speech," "reason," or "account"

Logos is a lightweight, flexible logging library for Go. It focuses on simplicity, clarity, and customizability—especially when it comes to log levels, output formatting, and structured logging.

Getting Started

import (
    "os"
    "github.com/goodblaster/logos"
)

func main() {
    log := logos.NewLogger(logos.LevelDebug, logos.FormatConsole, os.Stdout)
    log.Debug("Starting app...")
}

Global Logger

You can set a global logger to avoid passing it throughout your code:

logos.SetDefaultLogger(log)
logos.Info("This uses the default logger")

Features

  • Easily adjustable log levels
  • Structured field and error logging
  • Multiple built-in formatters (Text, JSON, Console)
  • Global and per-instance logging
  • Simple customization of level names and colors

Custom Log Levels

Unlike many logging packages, Logos allows you to rename or define your own log levels easily:

const (
    LevelApple logos.Level = iota
    LevelBanana
    LevelCherry
)

logos.LevelNames = map[logos.Level]string{
    LevelApple:  "apple",
    LevelBanana: "banana",
    LevelCherry: "cherry",
}

logos.LevelColors = map[logos.Level]logos.Color{
    LevelApple:  logos.ColorTextGreen,
    LevelBanana: logos.ColorTextYellow,
    LevelCherry: logos.ColorTextRed,
}

log := logos.NewLogger(LevelApple, logos.FormatConsole, os.Stdout)
log.Log(LevelApple, "apple log")
log.Log(LevelBanana, "banana log")
log.Log(LevelCherry, "cherry log")

Adding Fields and Errors

log.With("user_id", 42).Info("User logged in")
log.WithFields(map[string]any{"path": "/login", "method": "POST"}).Info("Handling request")
log.WithError(err).Error("Something went wrong")

Formatters

You can choose how logs are rendered:

  • FormatConsole — colorized terminal output
  • FormatText — plain, human-readable text
  • FormatJSON — structured JSON for machines

Conditional and Lazy Logging

log.LogFunc(logos.LevelDebug, func() string {
    return expensiveComputation()
})

log.LogIf(logos.LevelInfo, func() {
    fmt.Println("This block runs only if info level is enabled")
})

Default Log Levels

  • LevelDebug
  • LevelInfo
  • LevelWarn
  • LevelError
  • LevelFatal
  • LevelPrint

These can be extended or overridden to suit your needs.


Documentation

Index

Constants

View Source
const DefaultTimestampFormat = "2006-01-02T15:04:05"

DefaultTimestampFormat defines the layout used for default timestamps.

Variables

View Source
var DefaultConfig = Config{
	Timestamp: DefaultTimestamp,
}

DefaultConfig is the fallback configuration using the DefaultTimestamp function.

View Source
var FormatNames = map[Format]string{
	FormatJSON:    "JSON",
	FormatText:    "TEXT",
	FormatConsole: "CONSOLE",
}

FormatNames maps Format values to their string identifiers.

Formats is the list of all supported output formats.

View Source
var LevelColors map[Level]Color

LevelColors maps Level values to ANSI color codes for console output. This can be customized.

View Source
var LevelNames map[Level]string

LevelNames maps Level values to human-readable strings. This can be overridden by the user.

Functions

func Debug

func Debug(s ...any)

Debug logs a message at the debug level using the DefaultLogger.

func Debugf

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

Debugf logs a formatted message at the debug level using the DefaultLogger.

func DefaultTimestamp

func DefaultTimestamp() string

DefaultTimestamp returns the current local time formatted using DefaultTimestampFormat.

func Error

func Error(a ...any)

Error logs a message at the error level using the DefaultLogger.

func Errorf

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

Errorf logs a formatted message at the error level using the DefaultLogger.

func Fatal

func Fatal(a ...any)

Fatal logs a message at the fatal level using the DefaultLogger and panics.

func Fatalf

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

Fatalf logs a formatted message at the fatal level using the DefaultLogger and panics.

func Info

func Info(a ...any)

Info logs a message at the info level using the DefaultLogger.

func Infof

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

Infof logs a formatted message at the info level using the DefaultLogger.

func Log

func Log(level Level, a ...any)

Log logs a message at the specified level using the DefaultLogger.

func LogFunc

func LogFunc(level Level, msg func() string)

LogFunc logs a lazily-evaluated message using the DefaultLogger if the level is enabled.

func LogIf

func LogIf(level Level, log func())

LogIf executes a function if the level is enabled using the DefaultLogger.

func Logf

func Logf(level Level, format string, args ...any)

Logf logs a formatted message at the specified level using the DefaultLogger.

func Print

func Print(a ...any)

Print logs a message at the print level using the DefaultLogger.

func Printf

func Printf(format string, args ...any)

Printf logs a formatted message at the print level using the DefaultLogger.

func SetDefaultLogger

func SetDefaultLogger(logger Logger)

SetDefaultLogger overrides the global DefaultLogger with a new one.

func SetLevel

func SetLevel(level Level)

SetLevel sets the logging level of the DefaultLogger.

func Warn

func Warn(a ...any)

Warn logs a message at the warn level using the DefaultLogger.

func Warnf

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

Warnf logs a formatted message at the warn level using the DefaultLogger.

Types

type Color

type Color string

Color defines an ANSI escape sequence for terminal text and background coloring.

const (
	// ColorReset resets the terminal color to default.
	ColorReset Color = "\033[0m"

	// Foreground text colors.
	ColorTextRed     Color = "\033[31m"
	ColorTextYellow  Color = "\033[33m"
	ColorTextGreen   Color = "\033[32m"
	ColorTextBlue    Color = "\033[34m"
	ColorTextMagenta Color = "\033[35m"
	ColorTextCyan    Color = "\033[36m"
	ColorTextWhite   Color = "\033[37m"
	ColorTextPurple  Color = "\033[35m" // Alias for magenta
	ColorTextBlack   Color = "\033[30m"

	// Background colors.
	ColorBgRed     Color = "\033[41m"
	ColorBgYellow  Color = "\033[43m"
	ColorBgGreen   Color = "\033[42m"
	ColorBgBlue    Color = "\033[44m"
	ColorBgMagenta Color = "\033[45m"
	ColorBgCyan    Color = "\033[46m"
	ColorBgWhite   Color = "\033[47m"
	ColorBgBlack   Color = "\033[40m"
)

type Config

type Config struct {
	Timestamp func() string
}

Config defines the configuration for a Formatter, such as a custom timestamp function.

type Entry

type Entry struct {
	Fields Fields
	Msg    string
	Error  error
}

Entry holds the log data including fields, message, and error.

type Fields

type Fields = map[string]any

Fields represents a key-value pair used to annotate log entries.

type Format

type Format int

Format represents the output format used by the logger.

const (
	// FormatJSON outputs logs in structured JSON format.
	FormatJSON Format = iota
	// FormatText outputs logs as plain, uncolored text.
	FormatText
	// FormatConsole outputs logs as colored text suitable for terminals.
	FormatConsole
)

func (Format) String

func (f Format) String() string

String returns the string representation of a Format.

type Formatter

type Formatter interface {
	Format(level Level, entry Entry) string
}

Formatter is the interface implemented by all formatters in the package. It defines how a log entry is rendered as a string.

func ConsoleFormatter

func ConsoleFormatter() Formatter

ConsoleFormatter returns a new colorized console formatter with the default configuration.

func JSONFormatter

func JSONFormatter() Formatter

JSONFormatter returns a new JSON formatter with the default configuration.

func NewConsoleFormatter

func NewConsoleFormatter(cfg Config) Formatter

NewConsoleFormatter creates a new consoleFormatter using the provided configuration.

func NewFormatter

func NewFormatter(format Format) Formatter

NewFormatter returns a new Formatter based on the provided Format and the default configuration.

func NewFormatterWithConfig

func NewFormatterWithConfig(format Format, cfg Config) Formatter

NewFormatterWithConfig returns a new Formatter based on the provided Format and Config.

func NewJsonFormatter

func NewJsonFormatter(cfg Config) Formatter

NewJsonFormatter creates a new jsonFormatter using the provided configuration.

func NewTextFormatter

func NewTextFormatter(cfg Config) Formatter

NewTextFormatter creates a new textFormatter using the provided configuration.

func TextFormatter

func TextFormatter() Formatter

TextFormatter returns a new plain text formatter with the default configuration.

type Level

type Level int

Level represents the severity of a log message.

const (
	// LevelDebug represents fine-grained debug information.
	LevelDebug Level = iota - 1
	// LevelInfo represents general operational entries about what's going on inside the application.
	LevelInfo
	// LevelWarn represents potentially harmful situations.
	LevelWarn
	// LevelError represents error events that might still allow the application to continue running.
	LevelError
	// LevelFatal represents very severe error events that will presumably lead the application to abort.
	LevelFatal
	// LevelPrint is used for messages that should always be printed regardless of level filtering.
	LevelPrint = math.MaxInt
)

func (Level) String

func (level Level) String() string

String returns the string representation of a logging level.

type Logger

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

Logger is the primary struct for logging messages with optional fields and errors.

var DefaultLogger Logger

DefaultLogger is the global logger used by package-level log functions.

func NewLogger

func NewLogger(level Level, formatter Formatter, writer io.Writer) Logger

NewLogger creates a new Logger instance with the given level, formatter, and output writer.

func With

func With(key string, value any) Logger

With returns a copy of the DefaultLogger with an additional field.

func WithError

func WithError(err error) Logger

WithError returns a copy of the DefaultLogger with an associated error.

func WithFields

func WithFields(fields map[string]any) Logger

WithFields returns a copy of the DefaultLogger with additional fields.

func (Logger) Copy

func (logger Logger) Copy() Logger

Copy creates a deep copy of the logger, duplicating any fields.

func (Logger) Debug

func (logger Logger) Debug(a ...any)

Debug logs a message at the debug level.

func (Logger) Debugf

func (logger Logger) Debugf(format string, args ...any)

Debugf logs a formatted message at the debug level.

func (Logger) Error

func (logger Logger) Error(a ...any)

Error logs a message at the error level.

func (Logger) Errorf

func (logger Logger) Errorf(format string, args ...any)

Errorf logs a formatted message at the error level.

func (Logger) Fatal

func (logger Logger) Fatal(a ...any)

Fatal logs a message at the fatal level and then panics.

func (Logger) Fatalf

func (logger Logger) Fatalf(format string, args ...any)

Fatalf logs a formatted message at the fatal level and then panics.

func (Logger) Info

func (logger Logger) Info(a ...any)

Info logs a message at the info level.

func (Logger) Infof

func (logger Logger) Infof(format string, args ...any)

Infof logs a formatted message at the info level.

func (Logger) Log

func (logger Logger) Log(level Level, a ...any)

Log logs a message at the specified level.

func (Logger) LogFunc

func (logger Logger) LogFunc(level Level, msg func() string)

LogFunc evaluates the message-producing function only if the log level is enabled.

func (Logger) LogIf

func (logger Logger) LogIf(level Level, log func())

LogIf calls the provided function if the log level is enabled.

func (Logger) Logf

func (logger Logger) Logf(level Level, format string, args ...any)

Logf logs a formatted message at the specified level.

func (Logger) Print

func (logger Logger) Print(a ...any)

Print logs a message at the print level.

func (Logger) Printf

func (logger Logger) Printf(format string, args ...any)

Printf logs a formatted message at the print level.

func (Logger) SetLevel

func (logger Logger) SetLevel(level Level)

SetLevel sets the logging level of the logger.

func (Logger) Warn

func (logger Logger) Warn(a ...any)

Warn logs a message at the warn level.

func (Logger) Warnf

func (logger Logger) Warnf(format string, args ...any)

Warnf logs a formatted message at the warn level.

func (Logger) With

func (logger Logger) With(key string, value any) Logger

With returns a new Logger with an added single key-value field.

func (Logger) WithError

func (logger Logger) WithError(err error) Logger

WithError returns a new Logger with an associated error.

func (Logger) WithFields

func (logger Logger) WithFields(fields Fields) Logger

WithFields returns a new Logger with additional key-value pairs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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