另客网go项目公用的代码库

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package logrus
  2. // The following code was sourced and modified from the
  3. // https://github.com/tebeka/atexit package governed by the following license:
  4. //
  5. // Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. // this software and associated documentation files (the "Software"), to deal in
  9. // the Software without restriction, including without limitation the rights to
  10. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. // the Software, and to permit persons to whom the Software is furnished to do so,
  12. // subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in all
  15. // copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. import (
  24. "fmt"
  25. "os"
  26. )
  27. var handlers = []func(){}
  28. func runHandler(handler func()) {
  29. defer func() {
  30. if err := recover(); err != nil {
  31. fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
  32. }
  33. }()
  34. handler()
  35. }
  36. func runHandlers() {
  37. for _, handler := range handlers {
  38. runHandler(handler)
  39. }
  40. }
  41. // Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
  42. func Exit(code int) {
  43. runHandlers()
  44. os.Exit(code)
  45. }
  46. // RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
  47. // all handlers. The handlers will also be invoked when any Fatal log entry is
  48. // made.
  49. //
  50. // This method is useful when a caller wishes to use logrus to log a fatal
  51. // message but also needs to gracefully shutdown. An example usecase could be
  52. // closing database connections, or sending a alert that the application is
  53. // closing.
  54. func RegisterExitHandler(handler func()) {
  55. handlers = append(handlers, handler)
  56. }