log

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 7 Imported by: 16

README

Package log

Пакет log предоставляет функциональность для структурированного логирования с интеграцией в контекст приложения. Основан на zap с расширенными возможностями.

Types

Adapter

Структура RoundRobin реализует алгоритм балансировки нагрузки Round Robin.

Methods:

New(opts ...Option) (*Adapter, error)

Конструктор логгера. Поддерживает следующие опции:

  • WithDevelopmentMode() Option – включить логирование в режиме разработки
  • WithFileOutput(fileOutput file.Output) Option – добавить запись логов в файл
  • WithLevel(level Level) Option – изменить уровень логирования
NewFromConfig(config Config) (*Adapter, error)

Конструктор логгера через объект конфигурации.

(a *Adapter) Fatal(ctx context.Context, message any, fields ...Field)

Логирование сообщения с уровнем fatal.

(a *Adapter) Error(ctx context.Context, message any, fields ...Field)

Логирование сообщения с уровнем error.

(a *Adapter) Warn(ctx context.Context, message any, fields ...Field)

Логирование сообщения с уровнем warn.

(a *Adapter) Info(ctx context.Context, message any, fields ...Field)

Логирование сообщения с уровнем info.

(a *Adapter) Debug(ctx context.Context, message any, fields ...Field)

Логирование сообщения с уровнем debug.

(a *Adapter) Log(ctx context.Context, level Level, message any, fields ...Field)

Логирование сообщения с указанным уровнем level.

(a *Adapter) SetLevel(level Level)

Установить указанный уровень логирования.

(a *Adapter) Enabled(level Level) bool

Проверить активность указанного уровня логирования.

(a *Adapter) Sync() error

Синхронизация буферов логера.

(a *Adapter) Config() Config

Получить конфиг логера.

Functions

StdLoggerWithLevel(adapter Logger, level Level, withFields ...Field) *log.Logger

Преобразовать логера из текущего пакета в логер из стандартной библиотеки log

ContextLogValues(ctx context.Context) []Field

Получить поля для логов из контекста.

ToContext(ctx context.Context, kvs ...Field) context.Context

Добавить поля для логов в контекст.

RewriteContextField(ctx context.Context, field Field) context.Context

Перезаписать поле для логов в контексте.

UpsertContextField(ctx context.Context, field Field) context.Context

Перезаписать или записать поле для логов в контексте.

FromContext(ctx context.Context, key string) (Field, bool)

Получить поле для логов по ключу, если не найдено ok = false

CopyValues(ctxTo, ctxFrom context.Context) context.Context

Копирует в контекст все поля второго контекста

Usage

Default usage flow
package main

import (
	"context"
	"log"

	log2 "github.com/txix-open/isp-kit/log"
)

func main() {
	logger, err := log2.New(log2.WithLevel(log2.InfoLevel))
	if err != nil {
		log.Fatal(err)
	}

	/* store log fields in context */
	ctx := log2.ToContext(context.Background(),
		log2.String("requestId", "ff4488"),
		log2.String("secret", "x-secret-key"),
	)

	logger.Info(ctx, "hello world!",
		log2.String("service", "greetings-service"),
	)
	
	oldRequestId, ok := log2.FromContext(ctx, "requestId")
	if ok {
		ctx = log2.UpsertContextField(ctx, log2.String("requestId", "aa2266"))
		logger.Info(ctx, "new and old requestId",
			oldRequestId,
		)
    }
	
	

	/* change logger's level dynamically */
	logger.SetLevel(log2.DebugLevel)
	logger.Debug(ctx, "log level changed to debug")

	err = logger.Sync()
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package log provides a logging adapter built on top of Uber's Zap library. It supports structured logging with configurable output, log levels, and hooks.

Index

Constants

View Source
const (
	FatalLevel = zap.FatalLevel
	ErrorLevel = zap.ErrorLevel
	WarnLevel  = zap.WarnLevel
	InfoLevel  = zap.InfoLevel
	DebugLevel = zap.DebugLevel
)

Variables

This section is empty.

Functions

func CopyValues added in v1.66.0

func CopyValues(ctxTo context.Context, ctxFrom context.Context) context.Context

CopyValues copies logging fields from one context to another.

func RewriteContextField added in v1.33.0

func RewriteContextField(ctx context.Context, field Field) context.Context

RewriteContextField replaces a field in the context if it exists.

func StdLoggerWithLevel

func StdLoggerWithLevel(adapter Logger, level Level, withFields ...Field) *log.Logger

StdLoggerWithLevel wraps a Logger to provide a standard log.Logger interface.

func ToContext

func ToContext(ctx context.Context, kvs ...Field) context.Context

ToContext adds logging fields to a context.

func UpsertContextField added in v1.66.0

func UpsertContextField(ctx context.Context, field Field) context.Context

UpsertContextField replaces a field if it exists, or adds it if it doesn't.

Types

type Adapter

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

Adapter is the main logging implementation built on Zap.

func New

func New(opts ...Option) (*Adapter, error)

New creates a new Adapter with the provided options.

func NewFromConfig

func NewFromConfig(config Config) (*Adapter, error)

NewFromConfig creates a new Adapter from a Config.

func (*Adapter) Config

func (a *Adapter) Config() Config

Config returns the current configuration.

func (*Adapter) Debug

func (a *Adapter) Debug(ctx context.Context, message any, fields ...Field)

Debug logs a debug-level message.

func (*Adapter) Enabled

func (a *Adapter) Enabled(level Level) bool

Enabled checks if the specified level is enabled.

func (*Adapter) Error

func (a *Adapter) Error(ctx context.Context, message any, fields ...Field)

Error logs an error-level message.

func (*Adapter) Fatal

func (a *Adapter) Fatal(ctx context.Context, message any, fields ...Field)

Fatal logs a fatal-level message.

func (*Adapter) Info

func (a *Adapter) Info(ctx context.Context, message any, fields ...Field)

Info logs an informational message.

func (*Adapter) Log

func (a *Adapter) Log(ctx context.Context, level Level, message any, fields ...Field)

Log writes a log entry at the specified level.

func (*Adapter) SetLevel

func (a *Adapter) SetLevel(level Level)

SetLevel changes the current log level.

func (*Adapter) Sync

func (a *Adapter) Sync() error

Sync flushes any buffered log entries.

func (*Adapter) Warn

func (a *Adapter) Warn(ctx context.Context, message any, fields ...Field)

Warn logs a warning-level message.

type Config

type Config struct {
	// IsInDevMode enables development mode with human-friendly output.
	IsInDevMode bool
	// OutputPaths specifies the destinations for log output.
	OutputPaths []string
	// DisableDefaultOutput prevents logging to the default output.
	DisableDefaultOutput bool
	// SamplingConfig configures log message sampling.
	Sampling *SamplingConfig
	// Hooks is a slice of functions called for each log entry.
	Hooks []func(entry zapcore.Entry) error
	// InitialLevel sets the minimum log level.
	InitialLevel Level
}

Config holds the configuration for the logging adapter.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default settings.

type Field

type Field = zap.Field

Field is an alias for zap.Field representing a structured log field.

func Any

func Any(key string, value any) Field

Any creates a field from any type using Zap's automatic encoding.

func Bool

func Bool(key string, value bool) Field

Bool creates a boolean field.

func ByteString

func ByteString(key string, value []byte) Field

ByteString creates a byte slice field.

func ContextLogValues

func ContextLogValues(ctx context.Context) []Field

ContextLogValues extracts logging fields from a context.

func FromContext added in v1.66.0

func FromContext(ctx context.Context, key string) (Field, bool)

FromContext retrieves a field from the context by key.

func Int

func Int(key string, value int) Field

Int creates an int field.

func Int32

func Int32(key string, value int32) Field

Int32 creates an int32 field.

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field.

func String

func String(key string, value string) Field

String creates a string field.

type Level

type Level = zapcore.Level

Level is an alias for zapcore.Level representing log severity.

type Logger

type Logger interface {
	Error(ctx context.Context, message any, fields ...Field)
	Warn(ctx context.Context, message any, fields ...Field)
	Info(ctx context.Context, message any, fields ...Field)
	Debug(ctx context.Context, message any, fields ...Field)
}

Logger defines the interface for structured logging.

type Option

type Option func(cfg *Config)

Option is a function that configures a Config.

func WithDevelopmentMode

func WithDevelopmentMode() Option

WithDevelopmentMode enables development mode for human-friendly output.

func WithDisableDefaultOutput added in v1.64.2

func WithDisableDefaultOutput() Option

WithDisableDefaultOutput disables the default output.

func WithFileOutput

func WithFileOutput(fileOutput file.Output) Option

WithFileOutput adds a file output with rotation configuration.

func WithLevel

func WithLevel(level Level) Option

WithLevel sets the initial log level.

type SamplingConfig

type SamplingConfig = zap.SamplingConfig

SamplingConfig is an alias for zap.SamplingConfig.

Directories

Path Synopsis
Package file provides log file output with rotation using lumberjack.
Package file provides log file output with rotation using lumberjack.
Package logutil provides utility functions for logging.
Package logutil provides utility functions for logging.

Jump to

Keyboard shortcuts

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