logging

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 17 Imported by: 13

README

Station-Manager: logging module

This package provides a thin, concurrency-safe wrapper around rs/zerolog with a structured-first API, safe lifecycle (Initialize/Close), and file rotation via lumberjack.

Key features

  • Structured logging only (no Info/Infof helpers): prefer typed fields for queryability
  • Context loggers via With() for per-request scoping
  • Safe concurrent use; graceful shutdown waits for in-flight logs with a timeout
  • File rotation (size/age/backups), optional compression
  • Console writer options (no-color, custom time format)

Quick start

svc := &logging.Service{AppConfig: cfgService}
if err := svc.Initialize(); err != nil { panic(err) }
defer svc.Close()

// Basic structured entry
svc.InfoWith().Str("user_id", id).Int("count", 3).Msg("processed")

// Context (scoped) logger
req := svc.With().Str("request_id", reqID).Logger()
req.DebugWith().Str("path", path).Msg("incoming request")

// Nested structures
svc.InfoWith().Dict("db", func(e logging.LogEvent) {
    e.Str("op", "insert").Int("rows", 5)
}).Msg("batch")

Configuration (types.LoggingConfig)

Relevant fields (non-exhaustive):

  • Level: trace|debug|info|warn|error|fatal|panic
  • WithTimestamp: include timestamp field
  • SkipFrameCount: enable caller info with given skip frames when > 0
  • ConsoleLogging / FileLogging: enable writers; if both false, file logging is enabled by default
  • RelLogFileDir: relative directory for log files (validated for safety; created on init)
  • LogFileMaxBackups, LogFileMaxAgeDays, LogFileMaxSizeMB, LogFileCompress
  • ConsoleNoColor, ConsoleTimeFormat
  • ShutdownTimeoutMS, ShutdownTimeoutWarning

Shutdown semantics

On Close(), the service stops accepting new logs and waits for in-flight operations to finish up to ShutdownTimeoutMS (default 100ms). If the timeout elapses and ShutdownTimeoutWarning is true, a warning is emitted.

Dump helper

Dump(v any) recursively logs the content at Debug level, with depth/size limits. Intended for debugging; may delay shutdown if used right before Close().

Documentation

Index

Constants

View Source
const (
	ServiceName = types.LoggerServiceName //"logger"

)

Variables

This section is empty.

Functions

This section is empty.

Types

type LogContext

type LogContext interface {
	Str(key, val string) LogContext
	Strs(key string, vals []string) LogContext
	Int(key string, val int) LogContext
	Int64(key string, val int64) LogContext
	Uint(key string, val uint) LogContext
	Uint64(key string, val uint64) LogContext
	Float64(key string, val float64) LogContext
	Bool(key string, val bool) LogContext
	Time(key string, val time.Time) LogContext
	Err(err error) LogContext
	Interface(key string, val interface{}) LogContext
	// Logger creates and returns the new context logger
	Logger() Logger
}

LogContext provides a fluent interface for building a context logger with pre-populated fields. Fields added through LogContext will be included in all subsequent log messages.

type LogEvent

type LogEvent interface {
	Str(key, val string) LogEvent
	Strs(key string, vals []string) LogEvent
	Stringer(key string, val interface{ String() string }) LogEvent
	Int(key string, val int) LogEvent
	Int8(key string, val int8) LogEvent
	Int16(key string, val int16) LogEvent
	Int32(key string, val int32) LogEvent
	Int64(key string, val int64) LogEvent
	Uint(key string, val uint) LogEvent
	Uint8(key string, val uint8) LogEvent
	Uint16(key string, val uint16) LogEvent
	Uint32(key string, val uint32) LogEvent
	Uint64(key string, val uint64) LogEvent
	Float32(key string, val float32) LogEvent
	Float64(key string, val float64) LogEvent
	Bool(key string, val bool) LogEvent
	Bools(key string, vals []bool) LogEvent
	Time(key string, val time.Time) LogEvent
	Dur(key string, val time.Duration) LogEvent
	Err(err error) LogEvent
	AnErr(key string, err error) LogEvent
	Bytes(key string, val []byte) LogEvent
	Hex(key string, val []byte) LogEvent
	IPAddr(key string, val net.IP) LogEvent
	MACAddr(key string, val net.HardwareAddr) LogEvent
	Interface(key string, val interface{}) LogEvent
	Dict(key string, dict func(LogEvent)) LogEvent
	Msg(msg string)
	Msgf(format string, v ...interface{})
	Send()
}

LogEvent provides a fluent interface for structured logging with type-safe field methods. It wraps zerolog.Event to provide a clean API for adding typed fields to log entries.

type Logger

type Logger interface {
	TraceWith() LogEvent
	DebugWith() LogEvent
	InfoWith() LogEvent
	WarnWith() LogEvent
	ErrorWith() LogEvent
	FatalWith() LogEvent
	PanicWith() LogEvent

	// With for context logger creation
	// Creates a new logger with pre-populated fields that will be included in all subsequent logs
	// Example: reqLogger := logger.With().Str("request_id", id).Logger()
	With() LogContext
}

Logger exposes structured logging event builders. Usage pattern: logger.InfoWith().Str("user_id", id).Int("count", 5).Msg("processed") Create scoped loggers via With(): req := logger.With().Str("request_id", id).Logger() Then use req.InfoWith()/ErrorWith() etc. Note: string-format helpers (Info/Infof) are intentionally not provided; prefer structured logs.

type Service

type Service struct {
	WorkingDir    string          `di.inject:"WorkingDir"`
	AppConfig     *config.Service `di.inject:"appconfig"`
	LoggingConfig *types.LoggingConfig
	// contains filtered or unexported fields
}

func (*Service) Close

func (s *Service) Close() error

func (*Service) DebugWith

func (s *Service) DebugWith() LogEvent

DebugWith returns a LogEvent for structured Debug-level logging.

func (*Service) Dump

func (s *Service) Dump(v interface{})

Dump logs the contents of the provided value at Debug level. It handles various types including structs, maps, slices, and basic types. For structs, it logs all exported fields. For complex types like maps and slices, it logs their elements. For basic types, it logs their values.

func (*Service) ErrorWith

func (s *Service) ErrorWith() LogEvent

ErrorWith returns a LogEvent for structured Error-level logging. Example: logger.ErrorWith().Err(err).Str("operation", "database").Msg("Query failed")

func (*Service) FatalWith

func (s *Service) FatalWith() LogEvent

FatalWith returns a LogEvent for structured Fatal-level logging. The program will exit after the log is written.

func (*Service) InfoWith

func (s *Service) InfoWith() LogEvent

InfoWith returns a LogEvent for structured Info-level logging. Use this for queryable, structured logs instead of Info/Infof. Example: logger.InfoWith().Str("user_id", id).Int("count", 5).Msg("User processed")

func (*Service) Initialize

func (s *Service) Initialize() error

Initialize initializes the logger.

func (*Service) PanicWith

func (s *Service) PanicWith() LogEvent

PanicWith returns a LogEvent for structured Panic-level logging. The program will panic after the log is written.

func (*Service) TraceWith

func (s *Service) TraceWith() LogEvent

TraceWith returns a LogEvent for structured Trace-level logging. Trace is the most verbose logging level, typically used for very detailed debugging.

func (*Service) WarnWith

func (s *Service) WarnWith() LogEvent

WarnWith returns a LogEvent for structured Warn-level logging.

func (*Service) With

func (s *Service) With() LogContext

With returns a LogContext for creating a child logger with pre-populated fields. Example: reqLogger := logger.With().Str("request_id", id).Logger() Returns a no-op context if the service is not initialized.

Jump to

Keyboard shortcuts

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