Skip to content

Commit

Permalink
feat(xlog): add context support for shutdown timeout control
Browse files Browse the repository at this point in the history
  • Loading branch information
seefs001 committed Nov 4, 2024
1 parent 9930a82 commit 27b9533
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
6 changes: 4 additions & 2 deletions examples/xlog_example/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"os"
"os/signal"
"syscall"
Expand Down Expand Up @@ -89,9 +90,10 @@ func main() {
// Wait for interrupt signal
<-sigChan
xlog.Info("Shutting down application")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Perform shutdown tasks
if err := xlog.Shutdown(); err != nil {
if err := xlog.Shutdown(ctx); err != nil {
xlog.Error("Failed to shutdown logger", "error", err)
}

Expand Down
43 changes: 29 additions & 14 deletions xlog/xlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -694,27 +694,42 @@ type ShutdownHandler interface {
}

// Shutdown shuts down all handlers that implement the ShutdownHandler interface.
func Shutdown() error {
// If ctx is nil, it will use context.Background().
func Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}

mu.Lock()
defer mu.Unlock()

var errs []error
for _, handler := range handlers {
if closer, ok := handler.(ShutdownHandler); ok {
if err := closer.Shutdown(); err != nil {
errs = append(errs, fmt.Errorf("failed to shutdown handler: %w", err))
done := make(chan error, 1)
go func() {
var errs []error
for _, handler := range handlers {
if closer, ok := handler.(ShutdownHandler); ok {
if err := closer.Shutdown(); err != nil {
errs = append(errs, fmt.Errorf("failed to shutdown handler: %w", err))
}
}
}
if closer, ok := handler.(io.Closer); ok {
if err := closer.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to close handler: %w", err))
if closer, ok := handler.(io.Closer); ok {
if err := closer.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to close handler: %w", err))
}
}
}
if len(errs) > 0 {
done <- xerror.Errorf("failed to shutdown one or more handlers: %v", errs)
}
done <- nil
}()

select {
case err := <-done:
return err
case <-ctx.Done():
return xerror.Errorf("shutdown timeout: %v", ctx.Err())
}
if len(errs) > 0 {
return xerror.Errorf("failed to shutdown one or more handlers: %v", errs)
}
return nil
}

// SetLogger sets the default logger
Expand Down

0 comments on commit 27b9533

Please sign in to comment.