Documentation
¶
Overview ¶
Package graceful provides a Logger implementation using Go's log/slog.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Logger ¶
type Logger interface {
Infof(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
Logger interface is used throughout gorush
func NewSlogLogger ¶ added in v1.2.0
func NewSlogLogger(opts ...SlogLoggerOption) Logger
NewSlogLogger creates a Logger using flexible option pattern.
Usage:
NewSlogLogger() // text mode (default) NewSlogLogger(WithJSON()) // json mode NewSlogLogger(WithSlog(loggerObj)) // inject custom *slog.Logger, which overrides other options
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages the graceful shutdown process.
The Manager uses a singleton pattern - only one instance can exist per process. It handles OS signals (SIGINT, SIGTERM) and context cancellation to trigger shutdown.
Shutdown behavior:
- When a shutdown signal is received, all running jobs receive context cancellation
- Running jobs should respect context.Done() and exit gracefully
- After running jobs complete, shutdown jobs are executed in parallel
- If shutdown timeout is reached, remaining jobs are interrupted
Signal handling:
- Unix: SIGINT (Ctrl+C), SIGTERM (kill), SIGTSTP
- Windows: SIGINT, SIGTERM
- Note: This will override any existing signal.Notify() for these signals
Context behavior:
- If the parent context (from WithContext) is cancelled, shutdown is triggered
- ShutdownContext() returns a context that is cancelled when shutdown starts
- Done() returns a channel that is closed when all jobs complete
func GetManager ¶
func GetManager() *Manager
GetManager returns the existing Manager instance.
This will panic if NewManager() has not been called first. Use this in places where you need access to the manager but can't pass it directly.
Example:
// In main.go m := graceful.NewManager() // In another package m := graceful.GetManager() m.AddShutdownJob(cleanup)
func NewManager ¶
NewManager creates and initializes the graceful shutdown Manager.
This function uses a singleton pattern - calling it multiple times returns the same instance. The Manager automatically starts listening for OS signals (SIGINT, SIGTERM) and will trigger graceful shutdown when received.
Options:
- WithContext(ctx): Use a custom parent context. Shutdown triggers when context is cancelled.
- WithLogger(logger): Use a custom logger implementation.
- WithShutdownTimeout(duration): Set maximum time to wait for shutdown (default: 30s).
Example:
m := graceful.NewManager(
graceful.WithShutdownTimeout(10 * time.Second),
graceful.WithLogger(customLogger),
)
Important: Only one Manager can exist per process.
func NewManagerWithContext ¶ added in v0.0.2
NewManagerWithContext initial the Manager with custom context
func (*Manager) AddRunningJob ¶
func (g *Manager) AddRunningJob(f RunningJob)
AddRunningJob adds a long-running task that will receive shutdown signals via context.
Running jobs should:
- Monitor ctx.Done() and exit gracefully when signaled
- Return an error if something goes wrong
- Clean up resources before returning
Example:
m.AddRunningJob(func(ctx context.Context) error {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil // Graceful exit
case <-ticker.C:
// Do work
}
}
})
Note: This method is thread-safe. Panics are recovered and converted to errors.
func (*Manager) AddShutdownJob ¶ added in v0.0.2
func (g *Manager) AddShutdownJob(f ShutdownJob)
AddShutdownJob adds a shutdown task that will be executed when graceful shutdown is triggered.
Shutdown jobs are executed in parallel after all running jobs have completed. Each shutdown job should be idempotent as they may be called during unexpected shutdowns.
Note: This method is thread-safe and can be called from multiple goroutines. However, jobs added after shutdown has started will not be executed.
func (*Manager) Done ¶
func (g *Manager) Done() <-chan struct{}
Done returns a channel that is closed when all jobs (running + shutdown) have completed.
This should be used to block the main goroutine until graceful shutdown is complete:
m := graceful.NewManager() // ... add jobs ... <-m.Done() // Block until shutdown completes errs := m.Errors() // Check for errors
Warning: If you don't wait for Done(), your program may exit before cleanup completes, potentially causing goroutine leaks or incomplete shutdown.
func (*Manager) Errors ¶ added in v1.3.0
Errors returns all errors that occurred during running jobs and shutdown jobs.
This includes:
- Errors returned by running jobs
- Errors returned by shutdown jobs
- Panics recovered from jobs (converted to errors)
- Timeout errors if shutdown exceeded the configured timeout
The returned slice is a copy, so modifying it won't affect the internal state.
Example:
<-m.Done()
if errs := m.Errors(); len(errs) > 0 {
for _, err := range errs {
log.Printf("Shutdown error: %v", err)
}
os.Exit(1)
}
func (*Manager) ShutdownContext ¶ added in v0.0.4
ShutdownContext returns a context that is cancelled when shutdown begins.
Use this context for operations that should be cancelled during shutdown. This is the same context passed to running jobs.
Example:
ctx := m.ShutdownContext() req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) // Request will be cancelled when shutdown starts
type Option ¶
type Option interface {
Apply(*Options)
}
Option interface for configuration.
func WithShutdownTimeout ¶ added in v1.3.0
WithShutdownTimeout sets the maximum duration to wait for graceful shutdown to complete. If timeout is reached, the shutdown will proceed anyway and remaining jobs will be interrupted. A timeout of 0 means no timeout (wait indefinitely). Default is 30 seconds.
Example:
m := graceful.NewManager(
graceful.WithShutdownTimeout(10 * time.Second),
)
type OptionFunc ¶ added in v0.1.0
type OptionFunc func(*Options)
OptionFunc is a function that configures a graceful shutdown.
func (OptionFunc) Apply ¶ added in v0.1.0
func (f OptionFunc) Apply(option *Options)
Apply calls f(option)
type Options ¶ added in v0.1.0
type Options struct {
// contains filtered or unexported fields
}
Options for graceful shutdown
type RunningJob ¶
type ShutdownJob ¶ added in v1.3.0
type ShutdownJob func() error
type SlogLoggerOption ¶ added in v1.2.0
type SlogLoggerOption func(*slogLoggerOptions)
SlogLoggerOption applies configuration to NewSlogLogger.
func WithJSON ¶ added in v1.2.0
func WithJSON() SlogLoggerOption
WithJSON returns an option to set output as JSON format.
func WithSlog ¶ added in v1.2.0
func WithSlog(logger *slog.Logger) SlogLoggerOption
WithSlog injects a custom *slog.Logger instance.