Documentation
¶
Overview ¶
Package eventlogger provides structured logging capabilities for Observer pattern events.
This module acts as an Observer that can be registered with any Subject (like ObservableApplication) to log events to various output targets including console, files, and syslog.
Features ¶
The eventlogger module offers the following capabilities:
- Multiple output targets (console, file, syslog)
- Configurable log levels and formats
- Event type filtering
- Async processing with buffering
- Log rotation for file outputs
- Structured logging with metadata
- Error handling and recovery
Configuration ¶
The module can be configured through the EventLoggerConfig structure:
config := &EventLoggerConfig{ Enabled: true, LogLevel: "INFO", Format: "structured", BufferSize: 100, OutputTargets: []OutputTargetConfig{ { Type: "console", Level: "INFO", Console: &ConsoleTargetConfig{ UseColor: true, Timestamps: true, }, }, { Type: "file", Level: "DEBUG", File: &FileTargetConfig{ Path: "/var/log/modular-events.log", MaxSize: 100, MaxBackups: 5, Compress: true, }, }, }, }
Usage Examples ¶
Basic usage with ObservableApplication:
// Create application with observer support app := modular.NewObservableApplication(configProvider, logger) // Register event logger module eventLogger := eventlogger.NewModule() app.RegisterModule(eventLogger) // Initialize application (event logger will auto-register as observer) app.Init() // Now all application events will be logged according to configuration app.RegisterModule(&MyModule{}) // This will be logged app.Start() // This will be logged
Manual observer registration:
// Get the event logger service var logger *eventlogger.EventLoggerModule err := app.GetService("eventlogger.observer", &logger) // Register with any subject err = subject.RegisterObserver(logger, "user.created", "order.placed")
Event type filtering:
config := &EventLoggerConfig{ EventTypeFilters: []string{ "module.registered", "service.registered", "application.started", }, }
Output Formats ¶
The module supports different output formats:
**Text Format**: Human-readable format
2024-01-15 10:30:15 INFO [module.registered] Module 'auth' registered (type=AuthModule)
**JSON Format**: Machine-readable JSON
{"timestamp":"2024-01-15T10:30:15Z","level":"INFO","type":"module.registered","source":"application","data":{"moduleName":"auth","moduleType":"AuthModule"}}
**Structured Format**: Detailed structured format
[2024-01-15 10:30:15] INFO module.registered Source: application Data: moduleName: auth moduleType: AuthModule Metadata: {}
Error Handling ¶
The event logger handles errors gracefully:
- Output target failures don't stop other targets
- Buffer overflow is handled by dropping oldest events
- Invalid events are logged as errors
- Configuration errors are reported during initialization
Index ¶
- Constants
- Variables
- func NewModule() modular.Module
- type ConsoleTarget
- type ConsoleTargetConfig
- type EventLoggerConfig
- type EventLoggerModule
- func (m *EventLoggerModule) Constructor() modular.ModuleConstructor
- func (m *EventLoggerModule) Dependencies() []string
- func (m *EventLoggerModule) EmitEvent(ctx context.Context, event cloudevents.Event) error
- func (m *EventLoggerModule) GetRegisteredEventTypes() []string
- func (m *EventLoggerModule) Init(app modular.Application) error
- func (m *EventLoggerModule) Name() string
- func (m *EventLoggerModule) ObserverID() string
- func (m *EventLoggerModule) OnEvent(ctx context.Context, event cloudevents.Event) error
- func (m *EventLoggerModule) ProvidesServices() []modular.ServiceProvider
- func (m *EventLoggerModule) RegisterConfig(app modular.Application) error
- func (m *EventLoggerModule) RegisterObservers(subject modular.Subject) error
- func (m *EventLoggerModule) RequiresServices() []modular.ServiceDependency
- func (m *EventLoggerModule) Start(ctx context.Context) error
- func (m *EventLoggerModule) Stop(ctx context.Context) error
- type FileTarget
- type FileTargetConfig
- type LogEntry
- type OutputTarget
- type OutputTargetConfig
- type OutputTargetError
- type SyslogTarget
- type SyslogTargetConfig
Constants ¶
const ( // Logger lifecycle events EventTypeLoggerStarted = "com.modular.eventlogger.started" EventTypeLoggerStopped = "com.modular.eventlogger.stopped" // Event processing events EventTypeEventReceived = "com.modular.eventlogger.event.received" EventTypeEventProcessed = "com.modular.eventlogger.event.processed" EventTypeEventDropped = "com.modular.eventlogger.event.dropped" // Buffer events EventTypeBufferFull = "com.modular.eventlogger.buffer.full" // Output events EventTypeOutputSuccess = "com.modular.eventlogger.output.success" EventTypeOutputError = "com.modular.eventlogger.output.error" // Configuration events EventTypeConfigLoaded = "com.modular.eventlogger.config.loaded" EventTypeOutputRegistered = "com.modular.eventlogger.output.registered" )
Event type constants for eventlogger module events. Following CloudEvents specification reverse domain notation.
const ModuleName = "eventlogger"
ModuleName is the unique identifier for the eventlogger module.
const ServiceName = "eventlogger.observer"
ServiceName is the name of the service provided by this module.
Variables ¶
var ( // Configuration errors ErrInvalidLogLevel = errors.New("invalid log level") ErrInvalidFormat = errors.New("invalid log format") ErrInvalidFlushInterval = errors.New("invalid flush interval") ErrInvalidOutputType = errors.New("invalid output target type") ErrMissingFileConfig = errors.New("missing file configuration for file output target") ErrMissingFilePath = errors.New("missing file path for file output target") ErrMissingSyslogConfig = errors.New("missing syslog configuration for syslog output target") ErrInvalidSyslogNetwork = errors.New("invalid syslog network type") // Runtime errors ErrLoggerNotStarted = errors.New("event logger not started") ErrOutputTargetFailed = errors.New("output target failed") ErrEventBufferFull = errors.New("event buffer is full") ErrNoSubjectForEventEmission = errors.New("no subject available for event emission") ErrUnknownOutputTargetType = errors.New("unknown output target type") ErrFileNotOpen = errors.New("file not open") ErrSyslogWriterNotInit = errors.New("syslog writer not initialized") )
Error definitions for the eventlogger module
Functions ¶
Types ¶
type ConsoleTarget ¶
type ConsoleTarget struct {
// contains filtered or unexported fields
}
ConsoleTarget outputs events to console/stdout.
func NewConsoleTarget ¶
func NewConsoleTarget(config OutputTargetConfig, logger modular.Logger) *ConsoleTarget
NewConsoleTarget creates a new console output target.
func (*ConsoleTarget) Flush ¶
func (c *ConsoleTarget) Flush() error
Flush flushes console output (no-op for console).
func (*ConsoleTarget) Start ¶
func (c *ConsoleTarget) Start(ctx context.Context) error
Start initializes the console target.
func (*ConsoleTarget) Stop ¶
func (c *ConsoleTarget) Stop(ctx context.Context) error
Stop shuts down the console target.
func (*ConsoleTarget) WriteEvent ¶
func (c *ConsoleTarget) WriteEvent(entry *LogEntry) error
WriteEvent writes a log entry to console.
type ConsoleTargetConfig ¶
type ConsoleTargetConfig struct { // UseColor enables colored output for console UseColor bool `yaml:"useColor" default:"true" desc:"Enable colored console output"` // Timestamps determines if timestamps should be included Timestamps bool `yaml:"timestamps" default:"true" desc:"Include timestamps in console output"` }
ConsoleTargetConfig configures console output.
type EventLoggerConfig ¶
type EventLoggerConfig struct { // Enabled determines if event logging is active Enabled bool `yaml:"enabled" default:"true" desc:"Enable event logging"` // LogLevel determines which events to log (DEBUG, INFO, WARN, ERROR) LogLevel string `yaml:"logLevel" default:"INFO" desc:"Minimum log level for events"` // Format specifies the output format (text, json, structured) Format string `yaml:"format" default:"structured" desc:"Log output format"` // OutputTargets specifies where to output logs OutputTargets []OutputTargetConfig `yaml:"outputTargets" desc:"Output targets for event logs"` // EventTypeFilters allows filtering which event types to log EventTypeFilters []string `yaml:"eventTypeFilters" desc:"Event types to log (empty = all events)"` // BufferSize sets the size of the event buffer for async processing BufferSize int `yaml:"bufferSize" default:"100" desc:"Buffer size for async event processing"` // FlushInterval sets how often to flush buffered events FlushInterval time.Duration `yaml:"flushInterval" default:"5s" desc:"Interval to flush buffered events"` // IncludeMetadata determines if event metadata should be logged IncludeMetadata bool `yaml:"includeMetadata" default:"true" desc:"Include event metadata in logs"` // IncludeStackTrace determines if stack traces should be logged for error events IncludeStackTrace bool `yaml:"includeStackTrace" default:"false" desc:"Include stack traces for error events"` // StartupSync forces startup operational events (config loaded, outputs registered, logger started) // to be emitted synchronously during Start() instead of via async goroutine+sleep. StartupSync bool `yaml:"startupSync" default:"false" desc:"Emit startup operational events synchronously (no artificial sleep)"` // ShutdownEmitStopped controls whether a logger.stopped operational event is emitted. // When false, the module will not emit com.modular.eventlogger.stopped to avoid races with shutdown. ShutdownEmitStopped bool `yaml:"shutdownEmitStopped" default:"true" desc:"Emit logger stopped operational event on Stop"` // ShutdownDrainTimeout controls graceful shutdown behavior for in‑flight events. // If > 0: Stop() waits up to the specified duration then returns (remaining events may be dropped). // If <= 0: Stop() waits indefinitely for a full drain (lossless shutdown) unless the parent context cancels. // This explicit <= 0 contract avoids ambiguous huge timeouts and lets operators choose bounded vs. lossless. ShutdownDrainTimeout time.Duration `` /* 133-byte string literal not displayed */ }
EventLoggerConfig holds configuration for the event logger module.
func (*EventLoggerConfig) Validate ¶
func (c *EventLoggerConfig) Validate() error
Validate implements the ConfigValidator interface for EventLoggerConfig.
type EventLoggerModule ¶
type EventLoggerModule struct {
// contains filtered or unexported fields
}
EventLoggerModule provides structured logging for Observer pattern events. It implements both Observer and CloudEventObserver interfaces to receive events and log them to configured output targets. Supports both traditional ObserverEvents and CloudEvents for standardized event handling.
func (*EventLoggerModule) Constructor ¶
func (m *EventLoggerModule) Constructor() modular.ModuleConstructor
Constructor provides a dependency injection constructor for the module.
func (*EventLoggerModule) Dependencies ¶
func (m *EventLoggerModule) Dependencies() []string
Dependencies returns the names of modules this module depends on.
func (*EventLoggerModule) EmitEvent ¶
func (m *EventLoggerModule) EmitEvent(ctx context.Context, event cloudevents.Event) error
EmitEvent allows the module to emit its own operational events.
func (*EventLoggerModule) GetRegisteredEventTypes ¶
func (m *EventLoggerModule) GetRegisteredEventTypes() []string
GetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this eventlogger module can emit.
func (*EventLoggerModule) Init ¶
func (m *EventLoggerModule) Init(app modular.Application) error
Init initializes the eventlogger module with the application context.
func (*EventLoggerModule) Name ¶
func (m *EventLoggerModule) Name() string
Name returns the unique identifier for this module.
func (*EventLoggerModule) ObserverID ¶
func (m *EventLoggerModule) ObserverID() string
ObserverID returns the unique identifier for this observer.
func (*EventLoggerModule) OnEvent ¶
func (m *EventLoggerModule) OnEvent(ctx context.Context, event cloudevents.Event) error
OnEvent implements the Observer interface to receive and log CloudEvents.
func (*EventLoggerModule) ProvidesServices ¶
func (m *EventLoggerModule) ProvidesServices() []modular.ServiceProvider
ProvidesServices declares services provided by this module.
func (*EventLoggerModule) RegisterConfig ¶
func (m *EventLoggerModule) RegisterConfig(app modular.Application) error
RegisterConfig registers the module's configuration structure.
func (*EventLoggerModule) RegisterObservers ¶
func (m *EventLoggerModule) RegisterObservers(subject modular.Subject) error
RegisterObservers implements the ObservableModule interface to auto-register with the application as an observer.
func (*EventLoggerModule) RequiresServices ¶
func (m *EventLoggerModule) RequiresServices() []modular.ServiceDependency
RequiresServices declares services required by this module.
type FileTarget ¶
type FileTarget struct {
// contains filtered or unexported fields
}
FileTarget outputs events to a file with rotation support.
func NewFileTarget ¶
func NewFileTarget(config OutputTargetConfig, logger modular.Logger) (*FileTarget, error)
NewFileTarget creates a new file output target.
func (*FileTarget) Start ¶
func (f *FileTarget) Start(ctx context.Context) error
Start initializes the file target.
func (*FileTarget) Stop ¶
func (f *FileTarget) Stop(ctx context.Context) error
Stop shuts down the file target.
func (*FileTarget) WriteEvent ¶
func (f *FileTarget) WriteEvent(entry *LogEntry) error
WriteEvent writes a log entry to file.
type FileTargetConfig ¶
type FileTargetConfig struct { // Path specifies the log file path Path string `yaml:"path" required:"true" desc:"Path to log file"` // MaxSize specifies the maximum file size in MB before rotation MaxSize int `yaml:"maxSize" default:"100" desc:"Maximum file size in MB before rotation"` // MaxBackups specifies the maximum number of backup files to keep MaxBackups int `yaml:"maxBackups" default:"5" desc:"Maximum number of backup files"` // MaxAge specifies the maximum age in days to keep log files MaxAge int `yaml:"maxAge" default:"30" desc:"Maximum age in days to keep log files"` // Compress determines if rotated logs should be compressed Compress bool `yaml:"compress" default:"true" desc:"Compress rotated log files"` }
FileTargetConfig configures file output.
type LogEntry ¶
type LogEntry struct { Timestamp time.Time `json:"timestamp"` Level string `json:"level"` Type string `json:"type"` Source string `json:"source"` Data interface{} `json:"data"` Metadata map[string]interface{} `json:"metadata,omitempty"` }
LogEntry represents a log entry for an event.
type OutputTarget ¶
type OutputTarget interface { // Start initializes the output target Start(ctx context.Context) error // Stop shuts down the output target Stop(ctx context.Context) error // WriteEvent writes a log entry to the output target WriteEvent(entry *LogEntry) error // Flush ensures all buffered events are written Flush() error }
OutputTarget defines the interface for event log output targets.
func NewOutputTarget ¶
func NewOutputTarget(config OutputTargetConfig, logger modular.Logger) (OutputTarget, error)
NewOutputTarget creates a new output target based on configuration.
type OutputTargetConfig ¶
type OutputTargetConfig struct { // Type specifies the output type (console, file, syslog) Type string `yaml:"type" default:"console" desc:"Output target type"` // Level allows different log levels per target Level string `yaml:"level" default:"INFO" desc:"Minimum log level for this target"` // Format allows different formats per target Format string `yaml:"format" default:"structured" desc:"Log format for this target"` // Configuration specific to the target type Console *ConsoleTargetConfig `yaml:"console,omitempty" desc:"Console output configuration"` File *FileTargetConfig `yaml:"file,omitempty" desc:"File output configuration"` Syslog *SyslogTargetConfig `yaml:"syslog,omitempty" desc:"Syslog output configuration"` }
OutputTargetConfig configures a specific output target for event logs.
func (*OutputTargetConfig) Validate ¶
func (o *OutputTargetConfig) Validate() error
Validate validates an OutputTargetConfig.
type OutputTargetError ¶
OutputTargetError wraps errors from output target validation
func NewOutputTargetError ¶
func NewOutputTargetError(index int, err error) *OutputTargetError
NewOutputTargetError creates a new OutputTargetError
func (*OutputTargetError) Error ¶
func (e *OutputTargetError) Error() string
func (*OutputTargetError) Unwrap ¶
func (e *OutputTargetError) Unwrap() error
type SyslogTarget ¶
type SyslogTarget struct {
// contains filtered or unexported fields
}
SyslogTarget outputs events to syslog (supported on Unix-like systems).
func NewSyslogTarget ¶
func NewSyslogTarget(config OutputTargetConfig, logger modular.Logger) (*SyslogTarget, error)
NewSyslogTarget creates a new syslog output target.
func (*SyslogTarget) Flush ¶
func (s *SyslogTarget) Flush() error
Flush flushes syslog output (no-op for syslog).
func (*SyslogTarget) Start ¶
func (s *SyslogTarget) Start(ctx context.Context) error
Start initializes the syslog target.
func (*SyslogTarget) Stop ¶
func (s *SyslogTarget) Stop(ctx context.Context) error
Stop shuts down the syslog target.
func (*SyslogTarget) WriteEvent ¶
func (s *SyslogTarget) WriteEvent(entry *LogEntry) error
WriteEvent writes a log entry to syslog.
type SyslogTargetConfig ¶
type SyslogTargetConfig struct { // Network specifies the network type (tcp, udp, unix) Network string `yaml:"network" default:"unix" desc:"Network type for syslog connection"` // Address specifies the syslog server address Address string `yaml:"address" default:"" desc:"Syslog server address"` // Tag specifies the syslog tag Tag string `yaml:"tag" default:"modular" desc:"Syslog tag"` // Facility specifies the syslog facility Facility string `yaml:"facility" default:"user" desc:"Syslog facility"` }
SyslogTargetConfig configures syslog output.