logr

package module
v0.0.0-...-b002b92 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 5 Imported by: 0

README

🚀 Golr - Biblioteca de Logging Unificada para Go

Go Version License Go Report Card

Uma biblioteca de logging moderna e flexível para Go que oferece uma interface unificada para múltiplas implementações de logging, permitindo trocar entre diferentes backends sem alterar seu código.

✨ Características

  • 🎯 Interface Unificada: Uma única API para diferentes implementações de logging
  • 🔄 Múltiplos Backends: Suporte para atualmente slog (padrão Go) e zap (alta performance)
  • 🌐 Logging Global: Sistema de logging global opcional com funções de conveniência
  • 📝 Campos Estruturados: Sistema robusto de campos tipados
  • 🔗 Contexto: Propagação de campos via context
  • 📊 Múltiplos Outputs: Console e arquivo simultaneamente
  • 🔄 Rotação de Logs: Rotação automática com lumberjack
  • 🎨 Formatação Flexível: JSON e TEXT
  • 🛡️ Type Safety: Interface bem definida com validação de tipos

🚀 Instalação

go get github.com/BrunoTulio/logr

📖 Uso Básico

Logger Direto (Recomendado)
package main

import (
    "github.com/BrunoTulio/logr"
    "github.com/BrunoTulio/logr/adapters/slog.v1"
)

func main() {
    // Criar logger com slog (padrão do Go)
    logger := slog.New(
        slog.WithConsole(true),
        slog.WithConsoleLevel("INFO"),
        slog.WithConsoleFormatter("TEXT"),
    )
    
    logger.Info("Aplicação iniciada")
    logger.Error("Erro encontrado")
    
    // Com campos estruturados
    logger.WithFields(
        logr.String("user_id", "123"),
        logr.Bool("active", true),
    ).Info("Usuário logado")
}
Logger com Zap (Alta Performance)
package main

import (
    "github.com/BrunoTulio/logr"
    "github.com/BrunoTulio/logr/adapters/zap.v1"
)

func main() {
    // Criar logger com zap para alta performance
    logger := zap.New(
        zap.WithConsole(true),
        zap.WithConsoleLevel("INFO"),
        zap.WithConsoleFormatter("JSON"),
        zap.WithFile(true, "/var/log", "app.log"),
        zap.WithFileRotation(100, 30, true), // 100MB, 30 dias, comprimir
    )
    
    logger.Info("Sistema iniciado")
    
    // Com campos agrupados
    userLogger := logger.WithFields(
        logr.Group("user", 
            logr.String("name", "João"),
            logr.Bool("active", true),
        ),
        logr.Int("age", 30),
    )
    
    userLogger.Info("Usuário processado")
}
Logger Global (Opcional)
package main

import (
    "github.com/BrunoTulio/logr"
    "github.com/BrunoTulio/logr/adapters/slog.v1"
)

func main() {
    // Configurar o logger global (apenas se necessário)
    logger := slog.New(
        slog.WithConsole(true),
        slog.WithConsoleFormatter("JSON"),
    )
    
    logr.Set(logger)
    
    // Usar funções globais
    logr.Info("Usando logger global")
    logr.WithFields(
        logr.String("component", "global"),
    ).Info("Sistema inicializado")
}
Usando Contexto
package main

import (
    "context"
    "github.com/BrunoTulio/logr"
    "github.com/BrunoTulio/logr/adapters/slog.v1"
)

func processUser(ctx context.Context, userID string) {
    logger := slog.New(slog.WithConsole(true))
    
    // Adicionar campos ao contexto
    ctx = logger.WithFields(
        logr.String("request_id", "req-12345"),
        logr.String("user_id", userID),
    ).ToContext(ctx)
    
    // Em outra função
    processRequest(ctx)
}

func processRequest(ctx context.Context) {
    logger := slog.New(slog.WithConsole(true))
    requestLogger := logger.FromContext(ctx)
    
    requestLogger.Info("Processando requisição")
}

🔧 Configuração Avançada

Configuração Completa
// Com slog
logger := slog.New(
    slog.WithConsole(true),
    slog.WithConsoleLevel("DEBUG"),
    slog.WithConsoleFormatter("TEXT"),
    slog.WithAddSource(true),
    
    slog.WithFile(true, "/var/log", "application.log"),
    slog.WithFileLevel("INFO"),
    slog.WithFileFormatter("JSON"),
    slog.WithFileRotation(100, 30, true),
)

// Com zap
logger := zap.New(
    zap.WithConsole(true),
    zap.WithConsoleLevel("INFO"),
    zap.WithConsoleFormatter("JSON"),
    
    zap.WithFile(true, "/var/log", "application.log"),
    zap.WithFileLevel("DEBUG"),
    zap.WithFileFormatter("JSON"),
    zap.WithFileRotation(100, 30, true),
)

📊 Tipos de Campos Suportados

logger.WithFields(
    logr.String("name", "João"),
    logr.Bool("active", true),
    logr.Int("age", 30),
    logr.Uint64("id", 123456789),
    logr.Float64("score", 95.5),
    logr.Time("created_at", time.Now()),
    logr.Duration("duration", time.Second*5),
    logr.Group("address",
        logr.String("street", "Rua das Flores"),
        logr.String("city", "São Paulo"),
    ),
).Info("Dados do usuário")

🏗️ Arquitetura

golr/
├── logger.go          # Interface principal
├── level.go           # Níveis de log
├── field.go           # Sistema de campos
├── global.go          # Logger global (opcional)
├── noop.go           # Implementação vazia
└── adapters/
    ├── slog.v1/       # Implementação com slog (padrão Go)
    └── zap.v1/        # Implementação com zap (alta performance)

🎯 Vantagens de Usar golr

1. Flexibilidade
  • Troque entre implementações sem alterar o código
  • Configure diferentes outputs (console/arquivo) independentemente
  • Suporte a múltiplos formatos (JSON/TEXT)
2. Simplicidade
  • API limpa e intuitiva
  • Logger global opcional para casos específicos
  • Integração com context para propagação de campos
3. Performance
  • Escolha entre slog (padrão) e zap (alta performance)
  • Campos estruturados eficientes
  • Rotação de logs automática
4. Manutenibilidade
  • Interface bem definida
  • Código limpo e testável
  • Fácil de estender com novos adapters
5. Compatibilidade
  • Suporte ao slog padrão do Go 1.21+
  • Compatível com ferramentas de logging existentes
  • Migração fácil de outras bibliotecas

🔮 Implementações Futuras

🧪 Testes e Qualidade
  • Testes Unitários: Cobertura completa de todos os adapters
  • Testes de Integração: Testes end-to-end com diferentes configurações
  • Benchmarks: Comparação de performance entre adapters
  • CI/CD: Pipeline automatizado com GitHub Actions
📚 Documentação e Exemplos
  • Documentação da API: Godoc completo com exemplos
  • Best Practices: Padrões recomendados de uso
  • Tutorial Interativo: Exemplos práticos passo a passo
🔌 Adapters Disponíveis
🔌 Novos Adapters
  • Zerolog: Adapter para zerolog - JSON estruturado
  • Logrus: Adapter para logrus - Compatibilidade
🚀 Funcionalidades Avançadas
  • Sampling: Para logs de alta frequência
  • Métricas: Integração com Prometheus/OpenTelemetry
  • Buffering: Buffer configurável para melhor performance
  • Compressão: Compressão automática de logs antigos
  • Middleware: Intercepta o log antes de ser enviado ao destino final

🤝 Contribuindo

Contribuições são muito bem-vindas! Por favor:

  1. Fork o projeto
  2. Crie uma branch para sua feature (git checkout -b feature/AmazingFeature)
  3. Commit suas mudanças (git commit -m 'Add some AmazingFeature')
  4. Push para a branch (git push origin feature/AmazingFeature)
  5. Abra um Pull Request
Tipos de Contribuição
  • 🐛 Bug Fixes: Correção de bugs
  • New Features: Novas funcionalidades
  • 📚 Documentation: Melhorias na documentação
  • 🧪 Tests: Adição de testes
  • 🔌 New Adapters: Novos adapters para bibliotecas de logging
  • 🎨 UI/UX: Melhorias na experiência do usuário

📄 Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.

🙏 Agradecimentos

  • Go Slog - Pela interface padrão do Go
  • Uber Zap - Por inspirar a alta performance
  • Lumberjack - Pela rotação de logs
  • Zerolog - Por inspirar o JSON estruturado
  • Logrus - Por popularizar o logging estruturado

📞 Contato


Se este projeto foi útil, considere dar uma estrela!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(message string)

func Debugf

func Debugf(format string, args ...interface{})

func Error

func Error(message string)

func Errorf

func Errorf(format string, args ...interface{})

func Fatal

func Fatal(message string)

func Fatalf

func Fatalf(format string, args ...interface{})

func Info

func Info(message string)

func Infof

func Infof(format string, args ...interface{})

func Output

func Output() io.Writer

func ToContext

func ToContext(ctx context.Context) context.Context

func Warn

func Warn(message string)

func Warnf

func Warnf(format string, args ...interface{})

Types

type Field

type Field struct {
	Type  FieldType
	Key   string
	Value any
}

func Any

func Any(key string, value any) Field

func Bool

func Bool(key string, value bool) Field

func Duration

func Duration(key string, value time.Duration) Field

func Float64

func Float64(key string, value float64) Field

func Group

func Group(name string, fields ...Field) Field

func Int

func Int(key string, value int) Field

func String

func String(key, value string) Field

func Time

func Time(key string, value time.Time) Field

func Uint64

func Uint64(key string, value uint64) Field

type FieldType

type FieldType int
const (
	StringType FieldType = iota
	BoolType
	IntType
	Uint64Type
	Float64Type
	TimeType
	DurationType
	GroupType
	AnyType
)

type Fields

type Fields []Field

func GetFields

func GetFields() Fields

type Level

type Level int
const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
)

type Logger

type Logger interface {
	Info(message string)
	Infof(format string, args ...interface{})

	Warn(message string)
	Warnf(format string, args ...interface{})

	Error(message string)
	Errorf(format string, args ...interface{})

	Fatal(message string)
	Fatalf(format string, args ...interface{})

	Debug(message string)
	Debugf(format string, args ...interface{})

	WithFields(fields ...Field) Logger
	WithField(field Field) Logger
	WithMap(m map[string]any) Logger

	ToContext(ctx context.Context) context.Context
	FromContext(ctx context.Context) Logger
	GetFields() Fields

	Output() io.Writer

	Sync() error
}

func FromContext

func FromContext(ctx context.Context) Logger

func Get

func Get() Logger

func Set

func Set(logger Logger) Logger

func WithField

func WithField(field Field) Logger

func WithFields

func WithFields(field ...Field) Logger

func WithMap

func WithMap(m map[string]any) Logger

type Noop

type Noop struct{}

func (Noop) Debug

func (n Noop) Debug(message string)

Debug implements Logger.

func (Noop) Debugf

func (n Noop) Debugf(format string, args ...interface{})

Debugf implements Logger.

func (Noop) Error

func (n Noop) Error(message string)

Error implements Logger.

func (Noop) Errorf

func (n Noop) Errorf(format string, args ...interface{})

Errorf implements Logger.

func (Noop) Fatal

func (n Noop) Fatal(message string)

Fatal implements Logger.

func (Noop) Fatalf

func (n Noop) Fatalf(format string, args ...interface{})

Fatalf implements Logger.

func (Noop) FromContext

func (n Noop) FromContext(ctx context.Context) Logger

FromContext implements Logger.

func (Noop) GetFields

func (n Noop) GetFields() Fields

Fields implements Logger.

func (Noop) Info

func (n Noop) Info(message string)

Info implements Logger.

func (Noop) Infof

func (n Noop) Infof(format string, args ...interface{})

Infof implements Logger.

func (Noop) Output

func (n Noop) Output() io.Writer

Output implements Logger.

func (Noop) Panic

func (n Noop) Panic(message string)

Panic implements Logger.

func (Noop) Panicf

func (n Noop) Panicf(format string, args ...interface{})

Panicf implements Logger.

func (Noop) Sync

func (n Noop) Sync() error

func (Noop) ToContext

func (n Noop) ToContext(ctx context.Context) context.Context

ToContext implements Logger.

func (Noop) Warn

func (n Noop) Warn(message string)

Warn implements Logger.

func (Noop) Warnf

func (n Noop) Warnf(format string, args ...interface{})

Warnf implements Logger.

func (Noop) WithField

func (n Noop) WithField(field Field) Logger

WithField implements Logger.

func (Noop) WithFields

func (n Noop) WithFields(fields ...Field) Logger

WithFields implements Logger.

func (Noop) WithMap

func (n Noop) WithMap(m map[string]any) Logger

WithField implements Logger.

Directories

Path Synopsis
adapters

Jump to

Keyboard shortcuts

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