log

package
v1.64.6 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 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

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

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

	/* 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

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 RewriteContextField added in v1.33.0

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

func StdLoggerWithLevel

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

func ToContext

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

Types

type Adapter

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

func New

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

func NewFromConfig

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

func (*Adapter) Config

func (a *Adapter) Config() Config

func (*Adapter) Debug

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

func (*Adapter) Enabled

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

func (*Adapter) Error

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

func (*Adapter) Fatal

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

func (*Adapter) Info

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

func (*Adapter) Log

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

func (*Adapter) SetLevel

func (a *Adapter) SetLevel(level Level)

func (*Adapter) Sync

func (a *Adapter) Sync() error

func (*Adapter) Warn

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

type Config

type Config struct {
	IsInDevMode          bool
	OutputPaths          []string
	DisableDefaultOutput bool
	Sampling             *SamplingConfig
	Hooks                []func(entry zapcore.Entry) error
	InitialLevel         Level
}

func DefaultConfig

func DefaultConfig() *Config

type Field

type Field = zap.Field

func Any

func Any(key string, value any) Field

func Bool

func Bool(key string, value bool) Field

func ByteString

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

func ContextLogValues

func ContextLogValues(ctx context.Context) []Field

func Int

func Int(key string, value int) Field

func Int32

func Int32(key string, value int32) Field

func Int64

func Int64(key string, value int64) Field

func String

func String(key string, value string) Field

type Level

type Level = zapcore.Level

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

type Option

type Option func(cfg *Config)

func WithDevelopmentMode

func WithDevelopmentMode() Option

func WithDisableDefaultOutput added in v1.64.2

func WithDisableDefaultOutput() Option

func WithFileOutput

func WithFileOutput(fileOutput file.Output) Option

func WithLevel

func WithLevel(level Level) Option

type SamplingConfig

type SamplingConfig = zap.SamplingConfig

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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