MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+146
@@ -0,0 +1,146 @@
|
||||
# Package `log`
|
||||
|
||||
Пакет `log` предоставляет функциональность для структурированного логирования с интеграцией в контекст приложения.
|
||||
Основан на [zap](https://github.com/uber-go/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
|
||||
|
||||
```go
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// 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.
|
||||
package log
|
||||
|
||||
import (
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// Config holds the configuration for the logging adapter.
|
||||
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
|
||||
}
|
||||
|
||||
// SamplingConfig is an alias for zap.SamplingConfig.
|
||||
type SamplingConfig = zap.SamplingConfig
|
||||
|
||||
// DefaultConfig returns a Config with default settings.
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
InitialLevel: InfoLevel,
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
contextKeyValue = contextKey{}
|
||||
)
|
||||
|
||||
// ContextLogValues extracts logging fields from a context.
|
||||
func ContextLogValues(ctx context.Context) []Field {
|
||||
value, _ := ctx.Value(contextKeyValue).([]Field)
|
||||
return value
|
||||
}
|
||||
|
||||
// ToContext adds logging fields to a context.
|
||||
func ToContext(ctx context.Context, kvs ...Field) context.Context {
|
||||
existedValues := append(ContextLogValues(ctx), kvs...)
|
||||
return context.WithValue(ctx, contextKeyValue, existedValues)
|
||||
}
|
||||
|
||||
// RewriteContextField replaces a field in the context if it exists.
|
||||
func RewriteContextField(ctx context.Context, field Field) context.Context {
|
||||
existedValues := ContextLogValues(ctx)
|
||||
fields := make([]Field, 0, len(existedValues))
|
||||
|
||||
for i := range existedValues {
|
||||
if existedValues[i].Key == field.Key {
|
||||
fields = append(fields, field)
|
||||
} else {
|
||||
fields = append(fields, existedValues[i])
|
||||
}
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, contextKeyValue, fields)
|
||||
}
|
||||
|
||||
// UpsertContextField replaces a field if it exists, or adds it if it doesn't.
|
||||
func UpsertContextField(ctx context.Context, field Field) context.Context {
|
||||
var found bool
|
||||
existedValues := ContextLogValues(ctx)
|
||||
fields := make([]Field, 0, len(existedValues))
|
||||
|
||||
for i := range existedValues {
|
||||
if existedValues[i].Key == field.Key {
|
||||
fields = append(fields, field)
|
||||
found = true
|
||||
} else {
|
||||
fields = append(fields, existedValues[i])
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
fields = append(fields, field)
|
||||
}
|
||||
return context.WithValue(ctx, contextKeyValue, fields)
|
||||
}
|
||||
|
||||
// FromContext retrieves a field from the context by key.
|
||||
func FromContext(ctx context.Context, key string) (Field, bool) {
|
||||
existedValues := ContextLogValues(ctx)
|
||||
|
||||
for i := range existedValues {
|
||||
if existedValues[i].Key == key {
|
||||
return existedValues[i], true
|
||||
}
|
||||
}
|
||||
|
||||
return Field{}, false
|
||||
}
|
||||
|
||||
// CopyValues copies logging fields from one context to another.
|
||||
func CopyValues(ctxTo context.Context, ctxFrom context.Context) context.Context {
|
||||
return ToContext(ctxTo, ContextLogValues(ctxFrom)...)
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Field is an alias for zap.Field representing a structured log field.
|
||||
type Field = zap.Field
|
||||
|
||||
// String creates a string field.
|
||||
func String(key string, value string) Field {
|
||||
return zap.String(key, value)
|
||||
}
|
||||
|
||||
// Int creates an int field.
|
||||
func Int(key string, value int) Field {
|
||||
return zap.Int(key, value)
|
||||
}
|
||||
|
||||
// Int32 creates an int32 field.
|
||||
func Int32(key string, value int32) Field {
|
||||
return zap.Int32(key, value)
|
||||
}
|
||||
|
||||
// Int64 creates an int64 field.
|
||||
func Int64(key string, value int64) Field {
|
||||
return zap.Int64(key, value)
|
||||
}
|
||||
|
||||
// Bool creates a boolean field.
|
||||
func Bool(key string, value bool) Field {
|
||||
return zap.Bool(key, value)
|
||||
}
|
||||
|
||||
// ByteString creates a byte slice field.
|
||||
func ByteString(key string, value []byte) Field {
|
||||
return zap.ByteString(key, value)
|
||||
}
|
||||
|
||||
// Any creates a field from any type using Zap's automatic encoding.
|
||||
func Any(key string, value any) Field {
|
||||
return zap.Any(key, value)
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# Package `file`
|
||||
|
||||
Пакет `file` предоставляет функциональность для настройки файлового вывода логов с ротацией
|
||||
через [Lumberjack](https://github.com/natefinch/lumberjack).
|
||||
Интегрируется с [zap](https://github.com/uber-go/zap) как кастомный Sink.
|
||||
|
||||
## Types
|
||||
|
||||
### Output
|
||||
|
||||
Структура представляет собой конфигурацию вывода, в которой можно указать путь к файлу логов, максимальный размер
|
||||
файла (MB) до ротации, максимальный срок хранения файлов в днях, максимальное количество старых лог-файлов и функцию
|
||||
сжатия старых файлов.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `ConfigToUrl(r Output) *url.URL`
|
||||
|
||||
Сконвертировать Output в URL для `zap`.
|
||||
|
||||
#### `NewFileWriter(r Output) io.WriteCloser`
|
||||
|
||||
Создать логгер `lumberjack` с ротацией.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/file"
|
||||
)
|
||||
|
||||
func main() {
|
||||
output := file.Output{
|
||||
File: "app.log",
|
||||
MaxSizeMb: 100, /* Ротация при 100MB */
|
||||
MaxBackups: 3, /* Хранить 3 старых файла */
|
||||
Compress: true, /* Сжимать .gz */
|
||||
}
|
||||
|
||||
logger, err := log2.New(
|
||||
log2.WithLevel(log2.InfoLevel),
|
||||
log2.WithFileOutput(output),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
// Package file provides log file output with rotation using lumberjack.
|
||||
package file
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
lumberjackSchema = "lumberjack"
|
||||
)
|
||||
|
||||
// nolint:gochecknoinits
|
||||
func init() {
|
||||
err := zap.RegisterSink(lumberjackSchema, func(u *url.URL) (zap.Sink, error) {
|
||||
r, err := fileOutputConfigFromUrl(u)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal rotation config")
|
||||
}
|
||||
return newSink(NewFileWriter(*r)), nil
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Output configures log file rotation.
|
||||
type Output struct {
|
||||
// File is the path to the log file.
|
||||
File string
|
||||
// MaxSizeMb is the maximum file size in megabytes before rotation.
|
||||
MaxSizeMb int
|
||||
// MaxDays is the maximum number of days to retain old log files.
|
||||
MaxDays int
|
||||
// MaxBackups is the maximum number of old log files to retain.
|
||||
MaxBackups int
|
||||
// Compress enables compression of rotated log files.
|
||||
Compress bool
|
||||
}
|
||||
|
||||
// ConfigToUrl converts an Output configuration to a URL.
|
||||
func ConfigToUrl(r Output) *url.URL {
|
||||
values := url.Values{
|
||||
"file": {r.File},
|
||||
"maxSizeMb": {strconv.Itoa(r.MaxSizeMb)},
|
||||
"maxDays": {strconv.Itoa(r.MaxDays)},
|
||||
"maxBackups": {strconv.Itoa(r.MaxBackups)},
|
||||
"compress": {strconv.FormatBool(r.Compress)},
|
||||
}
|
||||
u := &url.URL{
|
||||
Scheme: lumberjackSchema,
|
||||
RawQuery: values.Encode(),
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// fileOutputConfigFromUrl parses an Output configuration from a URL.
|
||||
func fileOutputConfigFromUrl(u *url.URL) (*Output, error) {
|
||||
values, err := url.ParseQuery(u.RawQuery)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse lumberjack params")
|
||||
}
|
||||
file := values.Get("file")
|
||||
maxSizeMb, err := strconv.Atoi(values.Get("maxSizeMb"))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse maxSizeMb")
|
||||
}
|
||||
maxDays, err := strconv.Atoi(values.Get("maxDays"))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse maxDays")
|
||||
}
|
||||
maxBackups, err := strconv.Atoi(values.Get("maxBackups"))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse maxBackups")
|
||||
}
|
||||
compress, err := strconv.ParseBool(values.Get("compress"))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse compress")
|
||||
}
|
||||
return &Output{
|
||||
File: file,
|
||||
MaxSizeMb: maxSizeMb,
|
||||
MaxDays: maxDays,
|
||||
MaxBackups: maxBackups,
|
||||
Compress: compress,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewFileWriter creates a new log file writer with rotation.
|
||||
func NewFileWriter(r Output) io.WriteCloser {
|
||||
return &lumberjack.Logger{
|
||||
Filename: r.File,
|
||||
MaxSize: r.MaxSizeMb,
|
||||
MaxAge: r.MaxDays,
|
||||
MaxBackups: r.MaxBackups,
|
||||
Compress: r.Compress,
|
||||
}
|
||||
}
|
||||
|
||||
type sink struct {
|
||||
io.WriteCloser
|
||||
}
|
||||
|
||||
// Sync flushes buffered writes.
|
||||
func (s sink) Sync() error {
|
||||
return s.Close()
|
||||
}
|
||||
|
||||
// newSink wraps a writer as a Zap sink.
|
||||
func newSink(writer io.WriteCloser) sink {
|
||||
return sink{
|
||||
WriteCloser: writer,
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Logger defines the interface for structured logging.
|
||||
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)
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// Level is an alias for zapcore.Level representing log severity.
|
||||
type Level = zapcore.Level
|
||||
|
||||
const (
|
||||
FatalLevel = zap.FatalLevel
|
||||
ErrorLevel = zap.ErrorLevel
|
||||
WarnLevel = zap.WarnLevel
|
||||
InfoLevel = zap.InfoLevel
|
||||
DebugLevel = zap.DebugLevel
|
||||
)
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// Adapter is the main logging implementation built on Zap.
|
||||
type Adapter struct {
|
||||
cfg Config
|
||||
logger *zap.Logger
|
||||
level zap.AtomicLevel
|
||||
}
|
||||
|
||||
// New creates a new Adapter with the provided options.
|
||||
func New(opts ...Option) (*Adapter, error) {
|
||||
config := DefaultConfig()
|
||||
for _, opt := range opts {
|
||||
opt(config)
|
||||
}
|
||||
return NewFromConfig(*config)
|
||||
}
|
||||
|
||||
// NewFromConfig creates a new Adapter from a Config.
|
||||
func NewFromConfig(config Config) (*Adapter, error) {
|
||||
cfg := zap.NewProductionConfig()
|
||||
if config.IsInDevMode {
|
||||
cfg = zap.NewDevelopmentConfig()
|
||||
}
|
||||
cfg.DisableStacktrace = true
|
||||
cfg.DisableCaller = true
|
||||
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
cfg.Sampling = config.Sampling
|
||||
|
||||
if config.DisableDefaultOutput {
|
||||
cfg.OutputPaths = nil
|
||||
}
|
||||
|
||||
if len(config.OutputPaths) > 0 {
|
||||
cfg.OutputPaths = append(cfg.OutputPaths, config.OutputPaths...)
|
||||
}
|
||||
|
||||
level := zap.NewAtomicLevelAt(config.InitialLevel)
|
||||
cfg.Level = level
|
||||
|
||||
var opts []zap.Option
|
||||
if len(config.Hooks) > 0 {
|
||||
opts = append(opts, zap.Hooks(config.Hooks...))
|
||||
}
|
||||
|
||||
logger, err := cfg.Build(opts...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build logger")
|
||||
}
|
||||
|
||||
return &Adapter{
|
||||
cfg: config,
|
||||
logger: logger,
|
||||
level: level,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Fatal logs a fatal-level message.
|
||||
func (a *Adapter) Fatal(ctx context.Context, message any, fields ...Field) {
|
||||
a.Log(ctx, FatalLevel, message, fields...)
|
||||
}
|
||||
|
||||
// Error logs an error-level message.
|
||||
func (a *Adapter) Error(ctx context.Context, message any, fields ...Field) {
|
||||
a.Log(ctx, ErrorLevel, message, fields...)
|
||||
}
|
||||
|
||||
// Warn logs a warning-level message.
|
||||
func (a *Adapter) Warn(ctx context.Context, message any, fields ...Field) {
|
||||
a.Log(ctx, WarnLevel, message, fields...)
|
||||
}
|
||||
|
||||
// Info logs an informational message.
|
||||
func (a *Adapter) Info(ctx context.Context, message any, fields ...Field) {
|
||||
a.Log(ctx, InfoLevel, message, fields...)
|
||||
}
|
||||
|
||||
// Debug logs a debug-level message.
|
||||
func (a *Adapter) Debug(ctx context.Context, message any, fields ...Field) {
|
||||
a.Log(ctx, DebugLevel, message, fields...)
|
||||
}
|
||||
|
||||
// Log writes a log entry at the specified level.
|
||||
func (a *Adapter) Log(ctx context.Context, level Level, message any, fields ...Field) {
|
||||
entry := a.logger.Check(level, castString(message))
|
||||
if entry != nil {
|
||||
fields = append(fields, ContextLogValues(ctx)...)
|
||||
entry.Write(fields...)
|
||||
}
|
||||
}
|
||||
|
||||
// SetLevel changes the current log level.
|
||||
func (a *Adapter) SetLevel(level Level) {
|
||||
a.level.SetLevel(level)
|
||||
}
|
||||
|
||||
// Enabled checks if the specified level is enabled.
|
||||
func (a *Adapter) Enabled(level Level) bool {
|
||||
return a.level.Enabled(level)
|
||||
}
|
||||
|
||||
// Sync flushes any buffered log entries.
|
||||
func (a *Adapter) Sync() error {
|
||||
return a.logger.Sync()
|
||||
}
|
||||
|
||||
// Config returns the current configuration.
|
||||
func (a *Adapter) Config() Config {
|
||||
return a.cfg
|
||||
}
|
||||
|
||||
// StdLoggerWithLevel wraps a Logger to provide a standard log.Logger interface.
|
||||
func StdLoggerWithLevel(adapter Logger, level Level, withFields ...Field) *log.Logger {
|
||||
kitAdapter, ok := adapter.(*Adapter)
|
||||
if !ok {
|
||||
panic(fmt.Errorf("adapter must be a [%T], got [%T]", &Adapter{}, adapter)) // nolint:err113
|
||||
}
|
||||
logger := kitAdapter.logger.With(withFields...)
|
||||
stdLogger, err := zap.NewStdLogAt(logger, level)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return stdLogger
|
||||
}
|
||||
|
||||
// castString converts a value to a string representation.
|
||||
func castString(v any) string {
|
||||
switch typed := v.(type) {
|
||||
case string:
|
||||
return typed
|
||||
case error:
|
||||
return typed.Error()
|
||||
default:
|
||||
return fmt.Sprintf("%v", typed)
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# Package `logutil`
|
||||
|
||||
Пакет `logutil` предоставляет функции-утилиты для гибкого управления уровнем логирования ошибок.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `LogLevelForError(err error) log.Level`
|
||||
|
||||
Определить уровень логирования для ошибки.
|
||||
|
||||
#### `LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field)`
|
||||
|
||||
Получить функцию логирования соответствующего уровня для ошибки.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
)
|
||||
|
||||
type rateLimitError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e rateLimitError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (e rateLimitError) LogLevel() log2.Level {
|
||||
return log2.WarnLevel
|
||||
}
|
||||
|
||||
// Обработка ошибки
|
||||
func processRequest() error {
|
||||
/* put here logic with request */
|
||||
return rateLimitError{Message: "some error"}
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
err = processRequest()
|
||||
logFunc := logutil.LogLevelFuncForError(err, logger)
|
||||
logFunc(context.Background(),
|
||||
"Request processing failed",
|
||||
log2.String("error", err.Error()),
|
||||
)
|
||||
}
|
||||
|
||||
```
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
// Package logutil provides utility functions for logging.
|
||||
package logutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// LogLevelSpecifier is an interface for errors that specify their log level.
|
||||
type LogLevelSpecifier interface {
|
||||
LogLevel() log.Level
|
||||
}
|
||||
|
||||
// LogLevelForError determines the log level for an error.
|
||||
// It returns ErrorLevel by default, or a custom level if the error implements LogLevelSpecifier.
|
||||
func LogLevelForError(err error) log.Level {
|
||||
logLevel := log.ErrorLevel
|
||||
specifier, ok := err.(LogLevelSpecifier)
|
||||
if ok {
|
||||
logLevel = specifier.LogLevel()
|
||||
}
|
||||
return logLevel
|
||||
}
|
||||
|
||||
// LogLevelFuncForError returns the appropriate logging function for an error.
|
||||
// It uses LogLevelForError to determine the log level and returns the corresponding Logger method.
|
||||
func LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field) {
|
||||
logLevel := LogLevelForError(err)
|
||||
switch logLevel {
|
||||
case log.ErrorLevel:
|
||||
return logger.Error
|
||||
case log.WarnLevel:
|
||||
return logger.Warn
|
||||
case log.InfoLevel:
|
||||
return logger.Info
|
||||
case log.DebugLevel:
|
||||
return logger.Debug
|
||||
default:
|
||||
return logger.Error
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/log/file"
|
||||
)
|
||||
|
||||
// Option is a function that configures a Config.
|
||||
type Option func(cfg *Config)
|
||||
|
||||
// WithDevelopmentMode enables development mode for human-friendly output.
|
||||
func WithDevelopmentMode() Option {
|
||||
return func(a *Config) {
|
||||
a.IsInDevMode = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithFileOutput adds a file output with rotation configuration.
|
||||
func WithFileOutput(fileOutput file.Output) Option {
|
||||
return func(a *Config) {
|
||||
a.OutputPaths = append(a.OutputPaths, file.ConfigToUrl(fileOutput).String())
|
||||
}
|
||||
}
|
||||
|
||||
// WithDisableDefaultOutput disables the default output.
|
||||
func WithDisableDefaultOutput() Option {
|
||||
return func(a *Config) {
|
||||
a.DisableDefaultOutput = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithLevel sets the initial log level.
|
||||
func WithLevel(level Level) Option {
|
||||
return func(a *Config) {
|
||||
a.InitialLevel = level
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user