logger

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 24 Imported by: 0

README

logger

Structured Go logger built on log/slog with colored console output, component-aware prefixes, and rotating JSON log files.

Go Go report License

English | Russian

Features

  • Small logger API on top of slog.
  • Colored console logs with component and source location prefixes.
  • JSON logs to a rotating file or any custom io.Writer.
  • Built-in levels: trace, debug, info, warn, error, fatal.
  • Component scoping with Named(...) and WithComponent(...).
  • Context helpers for request-scoped logging.
  • Package-level default logger for quick integration.
  • Helpers for common slog.Attr values and errors.

Install

go get github.com/ra1phdd/logger

Quick Start

package main

import (
	"context"

	"github.com/ra1phdd/logger"
)

func main() {
	appLogger := logger.New(
		logger.WithLevelString("debug"),
		logger.WithComponent("api"),
		logger.WithFile("logs/app.log"),
	)

	appLogger.Info("service started", logger.String("addr", ":8080"))

	requestLogger := appLogger.Named("worker").With(
		logger.String("request_id", "42"),
	)
	ctx := logger.NewContext(context.Background(), requestLogger)

	logger.InfoContext(ctx, "job accepted", logger.Int("attempt", 1))
}

Output

  • Console output is human-readable and colorized through tint.
  • Each console message gets a prefix like <component> <file:line> >.
  • If no component is set explicitly, it is derived from the caller path.
  • Source resolution prefers an active caller inside the current project. If no project caller exists, Go module cache paths start at module@version, while other external absolute paths are reduced to the file name.
  • Absolute source paths outside the project are never emitted.
  • JSON output includes normalized level, source, and component fields.

By default:

  • console logs go to os.Stdout
  • JSON logs go to logs/<timestamp>.log
  • file output is disabled automatically under go test

File Rotation

Managed log files use lumberjack with these defaults:

  • max size: 64 MB
  • max backups: 32
  • max age: 30 days
  • compression: enabled
  • local time: enabled

Levels

Supported level strings:

  • trace
  • debug
  • info
  • warn or warning
  • error
  • fatal

You can change the level at construction time or later with:

  • WithLevel(level)
  • WithLevelString("debug")
  • (*Logger).SetLevel(level)
  • (*Logger).SetLogLevel("debug")
  • logger.SetLogLevel("debug")

Fatal writes the record and then calls the configured exit function. The default is os.Exit(1).

Options

  • WithLevel(level)
  • WithLevelString(level)
  • WithOutput(writer)
  • WithJSONOutput(writer)
  • WithFile(path)
  • WithoutFile()
  • WithComponent(name)
  • WithTimeFormat(layout)
  • WithNoColor(true)
  • WithExit(func(int))

Default Logger

Use Init(...) to configure the package-level logger:

logger.Init(
	logger.WithLevelString("info"),
	logger.WithComponent("app"),
)

logger.Info("ready")
logger.Warn("slow request", logger.Int("ms", 250))

Package-level Trace, Debug, Info, Warn, Error, and Fatal functions all use the default logger.

Context Helpers

  • NewContext(ctx, l) stores a logger in a context.
  • FromContext(ctx) returns the stored logger or the default logger.
  • TraceContext, DebugContext, InfoContext, WarnContext, ErrorContext, and FatalContext use the logger from the context.

Attr Helpers

The package re-exports common slog helpers:

  • Any
  • String
  • Int
  • Int64
  • Float64
  • Bool
  • Duration
  • Time

Use Err(err) to attach an error as error=<message>.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Any      = slog.Any
	String   = slog.String
	Int      = slog.Int
	Int64    = slog.Int64
	Float64  = slog.Float64
	Bool     = slog.Bool
	Duration = slog.Duration
	Time     = slog.Time
)

Functions

func Debug

func Debug(msg string, attrs ...Attr)

func DebugContext

func DebugContext(ctx context.Context, msg string, attrs ...Attr)

func Error

func Error(msg string, attrs ...Attr)

func ErrorContext

func ErrorContext(ctx context.Context, msg string, attrs ...Attr)

func Fatal

func Fatal(msg string, attrs ...Attr)

func FatalContext

func FatalContext(ctx context.Context, msg string, attrs ...Attr)

func GetLogLevel

func GetLogLevel() string

func Info

func Info(msg string, attrs ...Attr)

func InfoContext

func InfoContext(ctx context.Context, msg string, attrs ...Attr)

func Init

func Init(opts ...Option)

func NewContext

func NewContext(ctx context.Context, l *Logger) context.Context

func SetDefault

func SetDefault(l *Logger)

func SetLogLevel

func SetLogLevel(level string)

func Trace

func Trace(msg string, attrs ...Attr)

func TraceContext

func TraceContext(ctx context.Context, msg string, attrs ...Attr)

func Warn

func Warn(msg string, attrs ...Attr)

func WarnContext

func WarnContext(ctx context.Context, msg string, attrs ...Attr)

Types

type Attr

type Attr = slog.Attr

func Err

func Err(err error) Attr

type DeliveryConfig added in v1.0.2

type DeliveryConfig struct {
	BufferSize       int
	BatchSize        int
	FlushInterval    time.Duration
	MaxRetries       int
	ShutdownTimeout  time.Duration
	RetryInitialWait time.Duration
	RetryMaxWait     time.Duration
}

DeliveryConfig holds common delivery settings for HTTP sinks.

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

func Default

func Default() *Logger

func FromContext

func FromContext(ctx context.Context) *Logger

func Named

func Named(component string) *Logger

func New

func New(opts ...Option) *Logger

func With

func With(attrs ...Attr) *Logger

func (*Logger) Close added in v1.0.2

func (l *Logger) Close(ctx context.Context) error

Close gracefully shuts down all HTTP sinks, flushing any buffered records. It respects the context deadline for the shutdown timeout.

func (*Logger) Debug

func (l *Logger) Debug(msg string, attrs ...Attr)

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) Enabled

func (l *Logger) Enabled(ctx context.Context, level slog.Level) bool

func (*Logger) Error

func (l *Logger) Error(msg string, attrs ...Attr)

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, attrs ...Attr)

func (*Logger) FatalContext

func (l *Logger) FatalContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) GetLogLevel

func (l *Logger) GetLogLevel() string

func (*Logger) Handler

func (l *Logger) Handler() slog.Handler

func (*Logger) Info

func (l *Logger) Info(msg string, attrs ...Attr)

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) Level

func (l *Logger) Level() slog.Level

func (*Logger) Log

func (l *Logger) Log(ctx context.Context, level slog.Level, msg string, attrs ...Attr)

func (*Logger) Named

func (l *Logger) Named(component string) *Logger

func (*Logger) SetLevel

func (l *Logger) SetLevel(level slog.Level)

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(level string)

func (*Logger) Shutdown added in v1.0.2

func (l *Logger) Shutdown() error

Shutdown gracefully shuts down all sinks with default timeout.

func (*Logger) Slog

func (l *Logger) Slog() *slog.Logger

func (*Logger) Stats added in v1.0.3

func (l *Logger) Stats() []SinkStats

Stats returns operational statistics for all sinks. Returns a slice where each element corresponds to a sink (console, file, victorialogs, loki).

func (*Logger) Trace

func (l *Logger) Trace(msg string, attrs ...Attr)

func (*Logger) TraceContext

func (l *Logger) TraceContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) Warn

func (l *Logger) Warn(msg string, attrs ...Attr)

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, msg string, attrs ...Attr)

func (*Logger) With

func (l *Logger) With(attrs ...Attr) *Logger

func (*Logger) WithGroup

func (l *Logger) WithGroup(name string) *Logger

type LokiConfig added in v1.0.2

type LokiConfig struct {
	URL          string
	Labels       []string
	Delivery     DeliveryConfig
	StaticLabels map[string]string
}

LokiConfig configures the Loki sink.

type Option

type Option func(*config)

func WithComponent

func WithComponent(component string) Option

func WithConsoleLevel added in v1.0.2

func WithConsoleLevel(level slog.Level) Option

func WithConsoleLevelString added in v1.0.2

func WithConsoleLevelString(level string) Option

func WithExit

func WithExit(exit func(int)) Option

func WithFile

func WithFile(path string) Option

func WithJSONLevel added in v1.0.2

func WithJSONLevel(level slog.Level) Option

func WithJSONLevelString added in v1.0.2

func WithJSONLevelString(level string) Option

func WithJSONOutput

func WithJSONOutput(w io.Writer) Option

func WithLevel

func WithLevel(level slog.Level) Option

func WithLevelString

func WithLevelString(level string) Option

func WithLoki added in v1.0.2

func WithLoki(lokiCfg LokiConfig) Option

func WithNoColor

func WithNoColor(noColor bool) Option

func WithOutput

func WithOutput(w io.Writer) Option

func WithTimeFormat

func WithTimeFormat(format string) Option

func WithVictoriaLogs added in v1.0.2

func WithVictoriaLogs(vlCfg VictoriaLogsConfig) Option

func WithoutConsole added in v1.0.2

func WithoutConsole() Option

func WithoutFile

func WithoutFile() Option

type SinkStats added in v1.0.2

type SinkStats struct {
	DroppedOverflow         uint64
	DroppedRetriesExhausted uint64
	SendErrors              uint64
}

SinkStats is the public snapshot of sink operational metrics.

type SlogLogger

type SlogLogger = Logger

type VictoriaLogsConfig added in v1.0.2

type VictoriaLogsConfig struct {
	URL          string
	StreamFields []string
	Delivery     DeliveryConfig
	StaticLabels map[string]string
}

VictoriaLogsConfig configures the VictoriaLogs sink.

Jump to

Keyboard shortcuts

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