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
- Variables
- func Debug(msg string, fields ...map[string]interface{})
- func DurationFields(op string, d time.Duration) map[string]interface{}
- func Error(msg string, fields ...map[string]interface{})
- func ErrorFields(op string, err error) map[string]interface{}
- func Fatal(msg string, fields ...map[string]interface{})
- func Fields(kvs ...interface{}) map[string]interface{}
- func GetLoggerZ() zerolog.Logger
- func Info(msg string, fields ...map[string]interface{})
- func Init(cfg *Config)
- func MergeWithDuration(fields map[string]interface{}, d time.Duration) map[string]interface{}
- func MergeWithError(fields map[string]interface{}, err error) map[string]interface{}
- func Register(name string, l *Logger)
- func RegisterDefaults(names ...string)
- func SetGlobalLogger(l *Logger)
- func Warn(msg string, fields ...map[string]interface{})
- type ClientComponent
- type ComponentRegistry
- func (r *ComponentRegistry) APIPrefix() string
- func (r *ComponentRegistry) Clients() []ClientComponent
- func (r *ComponentRegistry) Consumers() []ConsumerComponent
- func (r *ComponentRegistry) Handlers() []HandlerComponent
- func (r *ComponentRegistry) Infrastructure() []InfraComponent
- func (r *ComponentRegistry) RegisterClient(name, target, status string)
- func (r *ComponentRegistry) RegisterConsumer(name, groupID, topic string, partitions int, status string)
- func (r *ComponentRegistry) RegisterHandler(method, path, handler string)
- func (r *ComponentRegistry) RegisterInfrastructure(name, componentType, status, details string)
- func (r *ComponentRegistry) RegisterRepository(name, store, status string)
- func (r *ComponentRegistry) RegisterService(name, status string, dependencies []string)
- func (r *ComponentRegistry) Repositories() []RepositoryComponent
- func (r *ComponentRegistry) Services() []ServiceComponent
- func (r *ComponentRegistry) SetAPIPrefix(prefix string)
- func (r *ComponentRegistry) SetHandlers(handlers []HandlerComponent)
- func (r *ComponentRegistry) StartTime() time.Time
- type Config
- type ConsumerComponent
- type HandlerComponent
- type InfraComponent
- type Logger
- func (l *Logger) Debug(msg string, fields ...map[string]interface{})
- func (l *Logger) Error(msg string, fields ...map[string]interface{})
- func (l *Logger) Fatal(msg string, fields ...map[string]interface{})
- func (l *Logger) GetLogger() zerolog.Logger
- func (l *Logger) Info(msg string, fields ...map[string]interface{})
- func (l *Logger) Warn(msg string, fields ...map[string]interface{})
- func (l *Logger) WithComponent(name string) *Logger
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithError(err error) *Logger
- func (l *Logger) WithFields(fields map[string]interface{}) *Logger
- type RepositoryComponent
- type ServiceComponent
Constants ¶
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.
const ( FormatPretty = "pretty" BooleanTrue = "true" )
Variables ¶
var ComponentRegistryInstance = NewComponentRegistry()
ComponentRegistryInstance is the global component registry.
Functions ¶
func DurationFields ¶
DurationFields creates fields for a timed operation.
func ErrorFields ¶
ErrorFields creates fields for an operation that failed.
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 ¶
GetLogger returns the underlying zerolog.Logger from the global logger (package-level).
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 ¶
MergeWithDuration adds a duration field to an existing map.
func MergeWithError ¶
MergeWithError adds an error field to an existing map.
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.
Types ¶
type ClientComponent ¶
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.
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 ¶
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 ¶
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 NewDefault ¶
NewDefault creates a logger with default configuration.
func NewFromEnv ¶
NewFromEnv creates a logger configured from environment variables.
func WithComponent ¶
WithComponent returns a component-tagged logger from the global logger.
func WithContext ¶
WithContext returns a context-enriched logger from the global logger.
func (*Logger) WithComponent ¶
WithComponent returns a logger tagged with a component name.
func (*Logger) WithContext ¶
WithContext returns a logger enriched with trace/span/request IDs from context.
func (*Logger) WithFields ¶
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.