logging

package
v1.19.3 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: GPL-3.0 Imports: 12 Imported by: 5

Documentation

Overview

Package logging provides tools for easy logging errors with traceback. Logging package is written over slog.Logger.

Index

Constants

This section is empty.

Variables

View Source
var Levels = struct {
	INFO, DEBUG, WARN, ERROR Level
}{
	INFO:  Level(slog.LevelInfo),
	DEBUG: Level(slog.LevelDebug),
	WARN:  Level(slog.LevelWarn),
	ERROR: Level(slog.LevelError),
}

Levels are a simple abstractions on slog.Level.

Functions

func GetLogTraceback

func GetLogTraceback(skipLevel int) string

GetLogTraceback return a string with info about filename, function name and line https://stackoverflow.com/questions/25927660/how-to-get-the-current-function-name

func LogDebugContext added in v1.19.1

func LogDebugContext(ctx context.Context, logger Logger, msg string, args ...any)

LogDebugContext — LogInfoContext на уровне DEBUG: те же поля Request ID и Traceback. Для строк, которые нужны только при отладке, — например, лог каждого HTTP-запроса.

func LogError added in v1.0.5

func LogError(logger Logger, msg string, err error, args ...any)

LogError logs error with message info, using provided logger.

func LogErrorContext added in v1.0.5

func LogErrorContext(ctx context.Context, logger Logger, msg string, err error, args ...any)

LogErrorContext uses provided logger to save error with message info and context. Context is used to get request ID and connect it with error.

func LogInfo added in v1.0.9

func LogInfo(logger Logger, msg string, args ...any)

LogInfo logs message, using provided logger.

func LogInfoContext added in v1.6.0

func LogInfoContext(ctx context.Context, logger Logger, msg string, args ...any)

LogInfoContext uses provided logger to save message info and context. Context is used to get request ID and connect it with error.

Types

type Config

type Config struct {
	Level       Level
	LogFilePath string
}

Config is a logging config, on base of which logger instance is created.

type DailyFile added in v1.19.1

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

DailyFile — io.Writer, пишущий в файл текущей даты: путь — pattern, где %s заменён датой в формате dateFormat и часовом поясе location (nil — UTC).

В полночь файл закрывается и открывается новый: файл прошлого дня перестаёт расти, и удаление по возрасту (mtime) его находит. Путь, посчитанный один раз на старте, давал файл на весь запуск: он рос до перезапуска, и срок хранения его не трогал — в него писали. Перезапуск в тот же день дописывает файл дня. Каталог создаётся, если его нет. Дата считается только при переходе через полночь, а не на каждой строке.

Файл не открылся — одно предупреждение в stdout на сбой и повтор не чаще раза в retryInterval; был открыт файл прошлой даты — строки идут в него.

func NewDailyFile added in v1.19.1

func NewDailyFile(pattern, dateFormat string, location *time.Location) *DailyFile

NewDailyFile — писатель в файл текущей даты. Файл открывается при первой записи.

func (*DailyFile) Close added in v1.19.1

func (d *DailyFile) Close() error

Close закрывает открытый файл.

func (*DailyFile) Write added in v1.19.1

func (d *DailyFile) Write(data []byte) (int, error)

Write пишет в файл текущей даты, в полночь переключаясь на новый.

type Level added in v1.5.0

type Level int

type Logger added in v1.5.0

type Logger interface {
	Debug(msg string, args ...any)
	DebugContext(ctx context.Context, msg string, args ...any)
	Info(msg string, args ...any)
	InfoContext(ctx context.Context, msg string, args ...any)
	Warn(msg string, args ...any)
	WarnContext(ctx context.Context, msg string, args ...any)
	Error(msg string, args ...any)
	ErrorContext(ctx context.Context, msg string, args ...any)
}

Logger interface is created for usage in external application according to "dependency inversion principle" of SOLID due to working via abstractions.

func New added in v1.5.1

func New(logLevel Level, logFilePath string) Logger

New implements as singleton pattern to get Logger instance, created once for whole app:.

func NewDaily added in v1.19.1

func NewDaily(logLevel Level, pattern, dateFormat string, location *time.Location) Logger

NewDaily — синглтон-логгер, как New, но файл лога — свой на каждую дату (DailyFile): pattern с %s под дату в формате dateFormat и поясе location.

New открывает один файл на весь запуск, и он растёт до перезапуска: срок хранения по возрасту (mtime) его не трогает — в него пишут. Синглтон у New и NewDaily общий: какой вызван первым, тот логгер и остаётся.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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