-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathatexit.go
69 lines (58 loc) · 1.54 KB
/
atexit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package log
import (
"fmt"
"os"
"sync"
)
var exitHandlers = []func(){}
var mux = &sync.Mutex{}
// runHandler tries to run exactly one handler and if not successful, writes error message to stderr
func runHandler(handler func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "error: atexit handler error:", err)
}
}()
handler()
}
// runHandlers is a helper function that runs all functions registered in exitHandlers
func runHandlers() {
for _, handler := range exitHandlers {
runHandler(handler)
}
}
// Exit runs all the exitHandlers and then terminates the program using
// os.Exit(code)
func Exit(code int) {
mux.Lock()
defer mux.Unlock()
runHandlers()
os.Exit(code)
}
// Exit runs all the exitHandlers and then terminates the program using
// os.Exit(code)
func (e *Entry) Exit(code int) {
Exit(code)
}
// Exit runs all the exitHandlers and then terminates the program using
// os.Exit(code)
func (l *Logger) Exit(code int) {
Exit(code)
}
// AddExitHandler adds a handler, call Exit in this module to invoke all exitHandlers.
// Thread safe
func AddExitHandler(handler func()) {
mux.Lock()
defer mux.Unlock()
exitHandlers = append(exitHandlers, handler)
}
// AddExitHandler adds a handler, call Exit in this module to invoke all exitHandlers.
// Thread safe
func (e *Entry) AddExitHandler(handler func()) {
AddExitHandler(handler)
}
// AddExitHandler adds a handler, call Exit in this module to invoke all exitHandlers.
// Thread safe
func (l *Logger) AddExitHandler(handler func()) {
AddExitHandler(handler)
}