Improved documentation of Fatal Handlers

This commit is contained in:
Aaron Greenlee 2016-07-15 22:56:31 -04:00
parent 1d4b5462f8
commit a283a10442
2 changed files with 22 additions and 1 deletions

View File

@ -384,3 +384,19 @@ assert.Equal("Hello error", hook.LastEntry().Message)
hook.Reset() hook.Reset()
assert.Nil(hook.LastEntry()) assert.Nil(hook.LastEntry())
``` ```
#### Fatal handlers
Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
```
...
handler := func() {
// gracefully shutdown something...
}
logrus.RegisterExitHandler(handler)
...
```

View File

@ -51,9 +51,14 @@ func Exit(code int) {
os.Exit(code) os.Exit(code)
} }
// RegisterExitHandler adds a Logrus atexit handler, call logrus.Exit to invoke // RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
// all handlers. The handlers will also be invoked when any Fatal log entry is // all handlers. The handlers will also be invoked when any Fatal log entry is
// made. // made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func RegisterExitHandler(handler func()) { func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler) handlers = append(handlers, handler)
} }