logger

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 8 Imported by: 16

README

logger

Structured logging built on zerolog with context propagation, component tagging, and field helpers.

Install

go get github.com/kbukum/gokit

Quick Start

package main

import "github.com/kbukum/gokit/logger"

func main() {
    log := logger.NewDefault("my-service")
    log.Info("server started", logger.Fields("port", 8080))

    // Component-scoped logger
    dbLog := log.WithComponent("database")
    dbLog.Error("connection failed", logger.ErrorFields("connect", err))

    // Global logger
    logger.SetGlobalLogger(log)
    logger.Info("using global logger")
}

Key Types & Functions

Name Description
Logger Structured logger wrapping zerolog
Config Logger configuration (level, format, output, rotation)
New() / NewDefault() / NewFromEnv() Logger constructors
WithContext() / WithComponent() / WithFields() Scoped logger builders
Debug() / Info() / Warn() / Error() / Fatal() Log methods (instance + global)
Fields() / ErrorFields() / DurationFields() Structured field helpers
SetGlobalLogger() / GetGlobalLogger() Global logger management
ComponentRegistry Tracks registered infrastructure and service components

⬅ Back to main README

Documentation

Overview

Package logger provides structured logging for gokit applications using zerolog.

It supports multiple output formats (JSON, console), log level configuration, and component-scoped loggers with structured fields.

Configuration

logger:
  level: "info"
  format: "json"

Usage

log := logger.Get("my-component")
log.Info().Str("key", "value").Msg("operation completed")

Index

Constants

View Source
const (
	FieldComponent     = "component"
	FieldTraceID       = "trace_id"
	FieldSpanID        = "span_id"
	FieldRequestID     = "request_id"
	FieldCorrelationID = "correlation_id"
	FieldUserID        = "user_id"
	FieldSessionID     = "session_id"
	FieldOperation     = "operation"
	FieldStatus        = "status"
	FieldError         = "error"
	FieldDuration      = "duration_ms"
	FieldPlatform      = "platform"
	FieldPhase         = "phase"
	FieldContainerID   = "container_id"
	FieldEmail         = "email"
)

Standard field key constants for structured logging.

View Source
const (
	FormatPretty = "pretty"
	BooleanTrue  = "true"
)

Variables

View Source
var ComponentRegistryInstance = NewComponentRegistry()

ComponentRegistryInstance is the global component registry.

Functions

func Debug

func Debug(msg string, fields ...map[string]interface{})

func DurationFields

func DurationFields(op string, d time.Duration) map[string]interface{}

DurationFields creates fields for a timed operation.

func Error

func Error(msg string, fields ...map[string]interface{})

func ErrorFields

func ErrorFields(op string, err error) map[string]interface{}

ErrorFields creates fields for an operation that failed.

func Fatal

func Fatal(msg string, fields ...map[string]interface{})

func Fields

func Fields(kvs ...interface{}) map[string]interface{}

Fields builds a map[string]interface{} from alternating key-value pairs.

logger.Info("done", logger.Fields("op", "save", "id", 42))

func GetLoggerZ

func GetLoggerZ() zerolog.Logger

GetLogger returns the underlying zerolog.Logger from the global logger (package-level).

func Info

func Info(msg string, fields ...map[string]interface{})

func Init

func Init(cfg *Config)

Init initializes the global logger from config. The service name used for the log tag comes from cfg.ServiceName. If empty, it defaults to the value set later by bootstrap (via SetGlobalLogger).

func MergeWithDuration

func MergeWithDuration(fields map[string]interface{}, d time.Duration) map[string]interface{}

MergeWithDuration adds a duration field to an existing map.

func MergeWithError

func MergeWithError(fields map[string]interface{}, err error) map[string]interface{}

MergeWithError adds an error field to an existing map.

func Register

func Register(name string, l *Logger)

Register stores a named logger in the registry.

func RegisterDefaults

func RegisterDefaults(names ...string)

RegisterDefaults registers a set of named loggers from the global config. Call this after Init() to seed the registry with common component loggers.

func SetGlobalLogger

func SetGlobalLogger(l *Logger)

SetGlobalLogger sets the global logger instance.

func Warn

func Warn(msg string, fields ...map[string]interface{})

Types

type ClientComponent

type ClientComponent struct {
	Name   string
	Target string // "gRPC:9090", "HTTP:8080"
	Status string
}

ClientComponent represents an external client (gRPC, HTTP, etc.).

type ComponentRegistry

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

ComponentRegistry tracks components during bootstrap for summary display.

func NewComponentRegistry

func NewComponentRegistry() *ComponentRegistry

NewComponentRegistry creates a new component registry.

func (*ComponentRegistry) APIPrefix

func (r *ComponentRegistry) APIPrefix() string

APIPrefix returns the configured API prefix.

func (*ComponentRegistry) Clients

func (r *ComponentRegistry) Clients() []ClientComponent

Clients returns all registered client components.

func (*ComponentRegistry) Consumers

func (r *ComponentRegistry) Consumers() []ConsumerComponent

Consumers returns all registered consumer components.

func (*ComponentRegistry) Handlers

func (r *ComponentRegistry) Handlers() []HandlerComponent

Handlers returns all registered handler components.

func (*ComponentRegistry) Infrastructure

func (r *ComponentRegistry) Infrastructure() []InfraComponent

Infrastructure returns all registered infrastructure components.

func (*ComponentRegistry) RegisterClient

func (r *ComponentRegistry) RegisterClient(name, target, status string)

RegisterClient registers an external client.

func (*ComponentRegistry) RegisterConsumer

func (r *ComponentRegistry) RegisterConsumer(name, groupID, topic string, partitions int, status string)

RegisterConsumer registers a message consumer.

func (*ComponentRegistry) RegisterHandler

func (r *ComponentRegistry) RegisterHandler(method, path, handler string)

RegisterHandler registers an HTTP handler.

func (*ComponentRegistry) RegisterInfrastructure

func (r *ComponentRegistry) RegisterInfrastructure(name, componentType, status, details string)

RegisterInfrastructure registers an infrastructure component.

func (*ComponentRegistry) RegisterRepository

func (r *ComponentRegistry) RegisterRepository(name, store, status string)

RegisterRepository registers a repository component.

func (*ComponentRegistry) RegisterService

func (r *ComponentRegistry) RegisterService(name, status string, dependencies []string)

RegisterService registers a service component.

func (*ComponentRegistry) Repositories

func (r *ComponentRegistry) Repositories() []RepositoryComponent

Repositories returns all registered repository components.

func (*ComponentRegistry) Services

func (r *ComponentRegistry) Services() []ServiceComponent

Services returns all registered service components.

func (*ComponentRegistry) SetAPIPrefix

func (r *ComponentRegistry) SetAPIPrefix(prefix string)

SetAPIPrefix sets the API prefix (for example "/api/v1") so route grouping can be done using the configured prefix instead of hard-coded values.

func (*ComponentRegistry) SetHandlers

func (r *ComponentRegistry) SetHandlers(handlers []HandlerComponent)

SetHandlers replaces the handler list (useful when collecting routes dynamically).

func (*ComponentRegistry) StartTime

func (r *ComponentRegistry) StartTime() time.Time

StartTime returns the registry creation time (bootstrap start).

type Config

type Config struct {
	Level       string `yaml:"level" mapstructure:"level"`
	Format      string `yaml:"format" mapstructure:"format"`
	Output      string `yaml:"output" mapstructure:"output"`
	NoColor     bool   `yaml:"no_color" mapstructure:"no_color"`
	Timestamp   bool   `yaml:"timestamp" mapstructure:"timestamp"`
	Caller      bool   `yaml:"caller" mapstructure:"caller"`
	Stacktrace  bool   `yaml:"stacktrace" mapstructure:"stacktrace"`
	MaxSize     int    `yaml:"max_size" mapstructure:"max_size"`       // megabytes
	MaxBackups  int    `yaml:"max_backups" mapstructure:"max_backups"` // number of backups
	MaxAge      int    `yaml:"max_age" mapstructure:"max_age"`         // days
	Compress    bool   `yaml:"compress" mapstructure:"compress"`
	LocalTime   bool   `yaml:"local_time" mapstructure:"local_time"`
	ServiceName string `yaml:"service_name" mapstructure:"service_name"` // used as tag in log output
}

Config contains logging configuration.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults applies default values to logging configuration.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates logging configuration.

type ConsumerComponent

type ConsumerComponent struct {
	Name       string
	Group      string
	Topic      string
	Partitions int
	Status     string
}

ConsumerComponent represents a message consumer (e.g. Kafka).

type HandlerComponent

type HandlerComponent struct {
	Method  string // "GET", "POST", etc.
	Path    string
	Handler string
}

HandlerComponent represents an HTTP handler/route.

type InfraComponent

type InfraComponent struct {
	Name    string
	Type    string // "database", "kafka", "redis", "server"
	Status  string // "active", "inactive", "error"
	Details string
}

InfraComponent represents an infrastructure dependency (database, cache, broker, etc.).

type Logger

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

Logger wraps zerolog.Logger with additional context.

func Get

func Get(name string) *Logger

Get retrieves a named logger. If the name is not registered it returns the global logger tagged with the requested component name.

func GetGlobalLogger

func GetGlobalLogger() *Logger

GetGlobalLogger returns the global logger, creating a default one if needed.

func New

func New(cfg *Config, serviceName string) *Logger

New creates a new logger instance with configuration.

func NewDefault

func NewDefault(serviceName string) *Logger

NewDefault creates a logger with default configuration.

func NewFromEnv

func NewFromEnv(serviceName string) *Logger

NewFromEnv creates a logger configured from environment variables.

func WithComponent

func WithComponent(name string) *Logger

WithComponent returns a component-tagged logger from the global logger.

func WithContext

func WithContext(ctx context.Context) *Logger

WithContext returns a context-enriched logger from the global logger.

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...map[string]interface{})

Debug logs a debug message.

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...map[string]interface{})

Error logs an error message.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...map[string]interface{})

Fatal logs a fatal message and exits.

func (*Logger) GetLogger

func (l *Logger) GetLogger() zerolog.Logger

GetLogger returns the underlying zerolog.Logger.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...map[string]interface{})

Info logs an info message.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...map[string]interface{})

Warn logs a warning message.

func (*Logger) WithComponent

func (l *Logger) WithComponent(name string) *Logger

WithComponent returns a logger tagged with a component name.

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a logger enriched with trace/span/request IDs from context.

func (*Logger) WithError

func (l *Logger) WithError(err error) *Logger

WithError returns a logger with an error field.

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields returns a logger with additional fields.

type RepositoryComponent

type RepositoryComponent struct {
	Name   string
	Store  string // "PostgreSQL", "Redis", etc.
	Status string
}

RepositoryComponent represents a data-access repository.

type ServiceComponent

type ServiceComponent struct {
	Name         string
	Status       string // "lazy", "initialized", "active"
	Dependencies []string
}

ServiceComponent represents a business-logic service.

Jump to

Keyboard shortcuts

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