core

package
v1.6.8 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package core provides the fundamental logging abstractions and implementations.

Package core contém funcionalidades centrais do logz.

Index

Constants

View Source
const (
	LevelNotice   kbx.Level = "notice"
	LevelDebug    kbx.Level = "debug"
	LevelTrace    kbx.Level = "trace"
	LevelSuccess  kbx.Level = "success"
	LevelInfo     kbx.Level = "info"
	LevelWarn     kbx.Level = "warn"
	LevelError    kbx.Level = "error"
	LevelFatal    kbx.Level = "fatal"
	LevelSilent   kbx.Level = "silent"
	LevelAlert    kbx.Level = "alert"
	LevelCritical kbx.Level = "critical"
	LevelAnswer   kbx.Level = "answer"
	LevelBug      kbx.Level = "bug"
	LevelPanic    kbx.Level = "panic"

	LevelNoticef   kbx.Level = "notice"
	LevelDebugf    kbx.Level = "debug"
	LevelTracef    kbx.Level = "trace"
	LevelSuccessf  kbx.Level = "success"
	LevelInfof     kbx.Level = "info"
	LevelWarnf     kbx.Level = "warn"
	LevelErrorf    kbx.Level = "error"
	LevelFatalf    kbx.Level = "fatal"
	LevelSilentf   kbx.Level = "silent"
	LevelAlertf    kbx.Level = "alert"
	LevelCriticalf kbx.Level = "critical"
	LevelAnswerf   kbx.Level = "answer"
	LevelBugf      kbx.Level = "bug"
	LevelPanicf    kbx.Level = "panic"

	LevelSprintf kbx.Level = "sprintf"
	LevelPrintln kbx.Level = "println"
	LevelLog     kbx.Level = "log"
	LevelPrint   kbx.Level = "print"
	LevelPrintf  kbx.Level = "printf"
	LevelLogf    kbx.Level = "logf"

	LevelDefault kbx.Level = "info"
)

Variables

This section is empty.

Functions

func DefaultEntryDecoder added in v1.5.6

func DefaultEntryDecoder(defaultLevel kbx.Level) func([]byte) (kbx.LogzEntry, error)

DefaultEntryDecoder cria uma função Decode pra IOBridge[*Entry], que transforma uma linha de texto em uma Entry simples.

É uma estratégia padrão: level fixo + mensagem = linha inteira.

func LoadFromEnvTyped added in v1.5.6

func LoadFromEnvTyped(key string, defaultValue any) any

func NewKbxEntry added in v1.6.3

func NewKbxEntry(level kbx.Level) (kbx.LogzEntry, error)

func NewLogzEntry added in v1.6.3

func NewLogzEntry(level kbx.Level) kbx.LogzEntry

func RegisterOptionSetter added in v1.5.6

func RegisterOptionSetter(key string, setter ConfigSetter)

Types

type ConfigSetter added in v1.5.6

type ConfigSetter func(l *Logger, value any)

ConfigSetter aplica uma opção no logger.

type Entry added in v1.5.6

type Entry struct {
	Timestamp time.Time `json:"ts" yaml:"ts" xml:"ts" mapstructure:"ts"`
	Level     kbx.Level `json:"level" yaml:"level" xml:"level" mapstructure:"level"`
	Message   string    `json:"msg" yaml:"msg" xml:"msg" mapstructure:"msg"`

	ShowColor   bool `json:"show_color,omitempty" yaml:"show_color,omitempty" xml:"show_color,omitempty" mapstructure:"show_color,omitempty"` // Habilita cores na saída
	ShowIcon    bool `json:"show_icon,omitempty" yaml:"show_icon,omitempty" xml:"show_icon,omitempty" mapstructure:"show_icon,omitempty"`     // Habilita ícones na saída
	ShowTraceID bool ``                                                                                                                       // Habilita o ID de rastreamento na saída
	/* 130-byte string literal not displayed */
	ShowCaller bool   `json:"show_caller,omitempty" yaml:"show_caller,omitempty" xml:"show_caller,omitempty" mapstructure:"show_caller,omitempty"` // Habilita informações do chamador na saída
	ShowStack  bool   `json:"show_stack,omitempty" yaml:"show_stack,omitempty" xml:"show_stack,omitempty" mapstructure:"show_stack,omitempty"`     // Habilita informações da pilha de chamadas na saída
	ShowFields bool   `json:"show_fields,omitempty" yaml:"show_fields,omitempty" xml:"show_fields,omitempty" mapstructure:"show_fields,omitempty"` // Habilita campos adicionais na saída
	Format     string `json:"format,omitempty" yaml:"format,omitempty" xml:"format,omitempty" mapstructure:"format,omitempty"`                     // json / text / xml / etc.

	Context  string `json:"ctx,omitempty" yaml:"ctx,omitempty" xml:"ctx,omitempty" mapstructure:"ctx,omitempty"`             // ex: "auth", "db", "billing"
	Source   string `json:"src,omitempty" yaml:"src,omitempty" xml:"src,omitempty" mapstructure:"src,omitempty"`             // componente/módulo/serviço
	TraceID  string `json:"trace,omitempty" yaml:"trace,omitempty" xml:"trace,omitempty" mapstructure:"trace,omitempty"`     // correlação
	Caller   string `json:"caller,omitempty" yaml:"caller,omitempty" xml:"caller,omitempty" mapstructure:"caller,omitempty"` // arquivo:linha função
	Severity int    `json:"sev,omitempty" yaml:"sev,omitempty" xml:"sev,omitempty" mapstructure:"sev,omitempty"`             // cache do Level.Severity()

	Tags   map[string]string `json:"tags,omitempty" yaml:"tags,omitempty" xml:"-" mapstructure:"tags,omitempty"`       // metadados arbitrários
	Fields map[string]any    `json:"fields,omitempty" yaml:"fields,omitempty" xml:"-" mapstructure:"fields,omitempty"` // dados estruturados arbitrários

	Error error `json:"error,omitempty"` // erro associado (se houver)
}

Entry é a unidade básica de log do sistema. Tudo no Kubex que for "log estruturado" deveria conseguir ser expresso nisso.

func NewEntry added in v1.5.6

func NewEntry(level kbx.Level) (*Entry, error)

func NewEntryImpl added in v1.5.6

func NewEntryImpl(level kbx.Level) (*Entry, error)

NewEntryImpl cria uma entry com: - timestamp UTC - maps inicializados - caller capturado

func ToEntry added in v1.5.6

func ToEntry(level kbx.Level, args ...any) *Entry

func (*Entry) CaptureCaller added in v1.5.6

func (e *Entry) CaptureCaller(skip int) kbx.Entry

func (*Entry) Clone added in v1.5.6

func (e *Entry) Clone() kbx.Entry

func (*Entry) Field added in v1.5.6

func (e *Entry) Field(k string, v any) kbx.Entry

func (*Entry) GetCaller added in v1.5.6

func (e *Entry) GetCaller() string

func (*Entry) GetContext added in v1.5.6

func (e *Entry) GetContext() string

func (*Entry) GetFields added in v1.5.6

func (e *Entry) GetFields() map[string]any

func (*Entry) GetFormat added in v1.6.3

func (e *Entry) GetFormat() string

func (*Entry) GetLevel added in v1.5.6

func (e *Entry) GetLevel() kbx.Level

func (*Entry) GetMessage added in v1.5.6

func (e *Entry) GetMessage() string

func (*Entry) GetPrefix added in v1.6.3

func (e *Entry) GetPrefix() string

func (*Entry) GetShowCaller added in v1.6.3

func (e *Entry) GetShowCaller() bool

func (*Entry) GetShowColor added in v1.6.3

func (e *Entry) GetShowColor() bool

func (*Entry) GetShowFields added in v1.6.3

func (e *Entry) GetShowFields() bool

func (*Entry) GetShowIcon added in v1.6.3

func (e *Entry) GetShowIcon() bool

func (*Entry) GetShowStack added in v1.6.3

func (e *Entry) GetShowStack() bool

func (*Entry) GetShowTraceID added in v1.6.3

func (e *Entry) GetShowTraceID() bool

func (*Entry) GetTags added in v1.5.6

func (e *Entry) GetTags() map[string]string

func (*Entry) GetTimestamp added in v1.5.6

func (e *Entry) GetTimestamp() time.Time

func (*Entry) GetTraceID added in v1.6.3

func (e *Entry) GetTraceID() string

func (*Entry) String added in v1.5.6

func (e *Entry) String() string

func (*Entry) Tag added in v1.5.6

func (e *Entry) Tag(k, v string) kbx.LogzEntry

func (*Entry) Validate added in v1.5.6

func (e *Entry) Validate() error

func (*Entry) WithCaller added in v1.5.6

func (e *Entry) WithCaller(c string) kbx.LogzEntry

func (*Entry) WithColor added in v1.6.3

func (e *Entry) WithColor(color bool) kbx.LogzEntry

func (*Entry) WithContext added in v1.5.6

func (e *Entry) WithContext(ctx string) kbx.LogzEntry

func (*Entry) WithData added in v1.5.6

func (e *Entry) WithData(data any) kbx.LogzEntry

func (*Entry) WithError added in v1.5.6

func (e *Entry) WithError(err error) kbx.LogzEntry

func (*Entry) WithField added in v1.5.6

func (e *Entry) WithField(key string, value any) kbx.LogzEntry

func (*Entry) WithFields added in v1.5.6

func (e *Entry) WithFields(fields map[string]any) kbx.LogzEntry

func (*Entry) WithFormat added in v1.6.3

func (e *Entry) WithFormat(format string) kbx.LogzEntry

func (*Entry) WithIcon added in v1.6.3

func (e *Entry) WithIcon(icon bool) kbx.LogzEntry

func (*Entry) WithLevel added in v1.5.6

func (e *Entry) WithLevel(l kbx.Level) kbx.LogzEntry

func (*Entry) WithMessage added in v1.5.6

func (e *Entry) WithMessage(msg string) kbx.LogzEntry

func (*Entry) WithShowCaller added in v1.6.3

func (e *Entry) WithShowCaller(show bool) kbx.LogzEntry

func (*Entry) WithShowFields added in v1.6.3

func (e *Entry) WithShowFields(show bool) kbx.LogzEntry

func (*Entry) WithShowTraceID added in v1.6.3

func (e *Entry) WithShowTraceID(show bool) kbx.LogzEntry

func (*Entry) WithSource added in v1.5.6

func (e *Entry) WithSource(src string) kbx.LogzEntry

func (*Entry) WithStack added in v1.6.3

func (e *Entry) WithStack(show bool) kbx.LogzEntry

func (*Entry) WithTraceID added in v1.5.6

func (e *Entry) WithTraceID(id string) kbx.LogzEntry

type IOBridge added in v1.5.6

type IOBridge[T kbx.Entry] struct {
	Logger *LoggerZ[T]
	Decode func([]byte) (T, error)
}

IOBridge é o adaptador que IMPLEMENTA io.Writer e empurra tudo para um Logger[T].

É aqui que o "modo B" (byte-first) entra no modo C híbrido: qualquer coisa que escreva em io.Writer pode ser redirecionada para o logger.

Exemplo de uso (lá fora, na superfície pública):

entryLogger := core.NewLogger[*core.Entry](formatter, os.Stdout, core.LevelInfo)
bridge      := core.NewIOBridge(entryLogger, core.DefaultEntryDecoder(core.LevelInfo))

log.SetOutput(bridge)      // log stdlib
cmd.Stdout = bridge        // exec.Command
json.NewEncoder(bridge)...

func NewIOBridge added in v1.5.6

func NewIOBridge[T kbx.Entry](logger *LoggerZ[T], decode func([]byte) (T, error)) *IOBridge[T]

NewIOBridge cria a ponte genérica entre io.Writer e Logger[T].

func (*IOBridge[T]) Write added in v1.5.6

func (b *IOBridge[T]) Write(p []byte) (int, error)

Write implementa io.Writer.

Estratégia básica (simples e eficaz): - recebe chunk de bytes - chama Decode pra produzir um T - passa pro Logger.Log

Se Logger ou Decode forem nil, a escrita é "dropada" mas não quebra a app.

type Logger added in v1.5.6

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

Logger é o núcleo do pipeline:

Record (T) -> hooks -> formatter -> io.Writer

Não sabe nada de linha, arquivo, CLI, JSON, etc. Isso é responsabilidade do Formatter + destino (io.Writer).

func NewLogger

func NewLogger(prefix string, opts *LoggerOptionsImpl, withDefaults bool) *Logger

func NewLoggerZI added in v1.5.6

func NewLoggerZI(prefix string, opts *LoggerOptionsImpl, withDefaults bool) *Logger

NewLoggerZI cria um logger genérico: - formatter: serializa Record em []byte - out: destino final (io.Writer global, arquivo, socket, etc) - min: nível mínimo

func (*Logger) AddHook added in v1.5.6

func (l *Logger) AddHook(h interfaces.Hook)

func (*Logger) Enabled added in v1.5.6

func (l *Logger) Enabled(level kbx.Level) bool

func (*Logger) GetConfig added in v1.5.6

func (l *Logger) GetConfig() *LoggerOptionsImpl

func (*Logger) GetLevel added in v1.5.6

func (l *Logger) GetLevel() kbx.Level

func (*Logger) GetMinLevel added in v1.5.6

func (l *Logger) GetMinLevel() kbx.Level

func (*Logger) Log added in v1.5.6

func (l *Logger) Log(lvl kbx.Level, rec ...any) error

Log é o caminho principal: recebe um Record pronto (T), dispara hooks, formata e escreve em out.

func (*Logger) LogAny added in v1.5.6

func (l *Logger) LogAny(level kbx.Level, args ...any) error

func (*Logger) SetBufferSize added in v1.5.6

func (l *Logger) SetBufferSize(size int)

SetBufferSize is the setter for setBufferSize

func (*Logger) SetCompress added in v1.5.6

func (l *Logger) SetCompress(compress bool)

SetCompress is the setter for setCompress

func (*Logger) SetConfig added in v1.6.3

func (l *Logger) SetConfig(opts *kbx.LogzConfig)

func (*Logger) SetFlushInterval added in v1.5.6

func (l *Logger) SetFlushInterval(interval time.Duration)

SetFlushInterval is the setter for setFlushInterval

func (*Logger) SetFormatter added in v1.5.6

func (l *Logger) SetFormatter(f formatter.Formatter)

func (*Logger) SetHooks added in v1.5.6

func (l *Logger) SetHooks(hooks []interfaces.Hook)

SetHooks is the setter for setHooks

func (*Logger) SetLHooks added in v1.5.6

func (l *Logger) SetLHooks(hooks interfaces.LHook[any])

SetLHooks is the setter for setLHooks

func (*Logger) SetMetadata added in v1.5.6

func (l *Logger) SetMetadata(metadata map[string]any)

SetMetadata is the setter for setMetadata

func (*Logger) SetMinLevel added in v1.5.6

func (l *Logger) SetMinLevel(min kbx.Level)

func (*Logger) SetOutput added in v1.5.6

func (l *Logger) SetOutput(w io.Writer)

func (*Logger) SetRotate added in v1.5.6

func (l *Logger) SetRotate(rotate bool)

SetRotate is the setter for setRotate

func (*Logger) SetRotateMaxAge added in v1.5.6

func (l *Logger) SetRotateMaxAge(age int64)

SetRotateMaxAge is the setter for setRotateMaxAge

func (*Logger) SetRotateMaxBack added in v1.5.6

func (l *Logger) SetRotateMaxBack(back int64)

SetRotateMaxBack is the setter for setRotateMaxBack

func (*Logger) SetRotateMaxSize added in v1.5.6

func (l *Logger) SetRotateMaxSize(size int64)

SetRotateMaxSize is the setter for setRotateMaxSize

type LoggerConfig added in v1.5.6

type LoggerConfig = kbx.InitArgs

type LoggerOptionsImpl added in v1.5.6

type LoggerOptionsImpl struct {
	*LoggerConfig        `json:",inline" yaml:",inline" mapstructure:",squash"`
	*LogzAdvancedOptions `json:",inline" yaml:",inline" mapstructure:",squash"`
}

func NewLoggerOptions added in v1.5.6

func NewLoggerOptions(initArgs *kbx.InitArgs) *LoggerOptionsImpl

func (*LoggerOptionsImpl) ApplyOptions added in v1.5.6

func (o *LoggerOptionsImpl) ApplyOptions(logger *Logger)

func (*LoggerOptionsImpl) Clone added in v1.5.6

func (*LoggerOptionsImpl) Get added in v1.5.6

func (o *LoggerOptionsImpl) Get(key string) any

func (*LoggerOptionsImpl) Hydrate added in v1.5.6

func (o *LoggerOptionsImpl) Hydrate(prefix string) *LoggerOptionsImpl

func (*LoggerOptionsImpl) Inherit added in v1.5.6

func (*LoggerOptionsImpl) Merge added in v1.5.6

func (*LoggerOptionsImpl) Set added in v1.5.6

func (o *LoggerOptionsImpl) Set(key string, value any)

func (*LoggerOptionsImpl) WithDefaults added in v1.5.6

func (o *LoggerOptionsImpl) WithDefaults(def *LoggerOptionsImpl) *LoggerOptionsImpl

type LoggerZ added in v1.5.6

type LoggerZ[T kbx.Entry] struct {
	ID uuid.UUID

	*Logger
	// contains filtered or unexported fields
}

LoggerZ é o núcleo do pipeline:

Record (T) -> hooks -> formatter -> io.Writer

Não sabe nada de linha, arquivo, CLI, JSON, etc. Isso é responsabilidade do Formatter + destino (io.Writer).

func NewLoggerZ added in v1.5.6

func NewLoggerZ[T kbx.Entry](prefix string, opts *LoggerOptionsImpl, withDefaults bool) *LoggerZ[T]

NewLoggerZ cria um logger genérico: - formatter: serializa T em []byte - out: destino final (io.Writer global, arquivo, socket, etc) - min: nível mínimo

func (*LoggerZ[T]) Alert added in v1.6.0

func (l *LoggerZ[T]) Alert(msg ...any)

func (*LoggerZ[T]) Alertf added in v1.6.0

func (l *LoggerZ[T]) Alertf(format string, args ...any)

func (*LoggerZ[T]) Answer added in v1.6.0

func (l *LoggerZ[T]) Answer(msg ...any)

func (*LoggerZ[T]) Answerf added in v1.6.0

func (l *LoggerZ[T]) Answerf(format string, args ...any)

func (*LoggerZ[T]) Bug added in v1.6.0

func (l *LoggerZ[T]) Bug(msg ...any)

func (*LoggerZ[T]) Bugf added in v1.6.0

func (l *LoggerZ[T]) Bugf(format string, args ...any)

func (*LoggerZ[T]) Clone added in v1.6.0

func (l *LoggerZ[T]) Clone() *LoggerZ[T]

func (*LoggerZ[T]) Critical added in v1.6.0

func (l *LoggerZ[T]) Critical(msg ...any)

func (*LoggerZ[T]) Criticalf added in v1.6.0

func (l *LoggerZ[T]) Criticalf(format string, args ...any)

func (*LoggerZ[T]) Debug added in v1.6.0

func (l *LoggerZ[T]) Debug(msg ...any)

Debug loga uma mensagem de debug

func (*LoggerZ[T]) Debugf added in v1.6.0

func (l *LoggerZ[T]) Debugf(format string, args ...any)

func (*LoggerZ[T]) Error added in v1.6.0

func (l *LoggerZ[T]) Error(msg ...any) error

Error loga um erro e retorna error

func (*LoggerZ[T]) Errorf added in v1.6.0

func (l *LoggerZ[T]) Errorf(format string, args ...any) error

func (*LoggerZ[T]) Fatal added in v1.6.0

func (l *LoggerZ[T]) Fatal(msg ...any)

Fatal loga uma mensagem fatal e encerra o programa com exit code 1

func (*LoggerZ[T]) Fatalf added in v1.6.0

func (l *LoggerZ[T]) Fatalf(format string, args ...any)

func (*LoggerZ[T]) Info added in v1.6.0

func (l *LoggerZ[T]) Info(msg ...any)

Info loga uma mensagem informativa

func (*LoggerZ[T]) Infof added in v1.6.0

func (l *LoggerZ[T]) Infof(format string, args ...any)

func (*LoggerZ[T]) Notice added in v1.6.0

func (l *LoggerZ[T]) Notice(msg ...any)

Notice loga uma mensagem de notice

func (*LoggerZ[T]) Noticef added in v1.6.0

func (l *LoggerZ[T]) Noticef(format string, args ...any)

func (*LoggerZ[T]) Panic added in v1.6.0

func (l *LoggerZ[T]) Panic(msg ...any)

func (*LoggerZ[T]) Panicf added in v1.6.0

func (l *LoggerZ[T]) Panicf(format string, args ...any)

func (*LoggerZ[T]) Printf added in v1.6.0

func (l *LoggerZ[T]) Printf(format string, args ...any)

func (*LoggerZ[T]) Println added in v1.6.0

func (l *LoggerZ[T]) Println(msg ...any)

func (*LoggerZ[T]) SetDebugMode added in v1.6.0

func (l *LoggerZ[T]) SetDebugMode(debug bool)

SetDebugMode habilita ou desabilita o modo debug do logger global. Quando debug=true, mostra logs de todos os níveis (incluindo debug e trace). Quando debug=false, mostra apenas logs de nível info ou superior.

func (*LoggerZ[T]) Success added in v1.6.0

func (l *LoggerZ[T]) Success(msg ...any)

Success loga uma mensagem de sucesso

func (*LoggerZ[T]) Successf added in v1.6.0

func (l *LoggerZ[T]) Successf(format string, args ...any)

func (*LoggerZ[T]) Trace added in v1.6.0

func (l *LoggerZ[T]) Trace(msg ...any)

func (*LoggerZ[T]) Tracef added in v1.6.0

func (l *LoggerZ[T]) Tracef(format string, args ...any)

func (*LoggerZ[T]) Warn added in v1.6.0

func (l *LoggerZ[T]) Warn(msg ...any)

Warn loga um aviso

func (*LoggerZ[T]) Warnf added in v1.6.0

func (l *LoggerZ[T]) Warnf(format string, args ...any)

type LogzAdvancedOptions added in v1.5.6

type LogzAdvancedOptions struct {
	// Hooks
	Formatter formatter.Formatter   `json:"formatter,omitempty" yaml:"formatter,omitempty" mapstructure:"formatter,omitempty"`
	Hooks     []interfaces.Hook     `json:"hooks,omitempty" yaml:"hooks,omitempty" mapstructure:"hooks,omitempty"`
	LHooks    interfaces.LHook[any] `json:"l_hooks,omitempty" yaml:"l_hooks,omitempty" mapstructure:"l_hooks,omitempty"`
	Metadata  map[string]any        `json:"metadata,omitempty" yaml:"metadata,omitempty" mapstructure:"metadata,omitempty"`
}

Jump to

Keyboard shortcuts

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