This repository has been archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
trace.go
125 lines (98 loc) · 2.19 KB
/
trace.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package trace
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sync"
)
var (
enabled = true
output = io.Writer(os.Stdout)
lock = sync.Mutex{}
)
// Enable enables tracing.
func Enable() {
lock.Lock()
defer lock.Unlock()
enabled = true
}
// Disable disables tracing.
func Disable() {
lock.Lock()
defer lock.Unlock()
enabled = false
}
// SetWriter sets the output of trace lines
// to an io.Writer.
func SetWriter(writer io.Writer) {
lock.Lock()
defer lock.Unlock()
output = writer
}
// SetOutputFile creates a file at filename and sets it as the output destination.
// If filename points to an existing file, it will be truncated. An error is returned
// if the file could not be opened.
func SetOutputFile(filename string) error {
lock.Lock()
defer lock.Unlock()
f, err := os.Create(filename)
if err != nil {
return err
}
output = f
return nil
}
// goroutineNum returns the goroutine number
// the caller is running on.
func goroutineNum() int {
b := make([]byte, 20)
runtime.Stack(b, false)
var goroutineNum int
fmt.Sscanf(string(b), "goroutine %d ", &goroutineNum)
return goroutineNum
}
func getTraceLine() string {
pc, file, line, ok := runtime.Caller(2)
if !ok {
return ""
}
caller := runtime.FuncForPC(pc)
goroutine := goroutineNum()
return fmt.Sprintf("[goroutine %d] %s:%d %s",
goroutine, filepath.Base(file), line, caller.Name())
}
// Trace prints the goroutine number, file, line number, and name
// of the calling function, as well as any optional arguments.
func Trace(args ...interface{}) {
if !enabled {
return
}
traceLine := getTraceLine()
if traceLine == "" {
return
}
message := fmt.Sprint(args...)
if message != "" {
message = "[" + message + "]"
}
fmt.Fprintln(output, traceLine, message)
}
// Tracef prints the goroutine number, file, line number, and name
// of the calling function, as well as any optional arguments printed
// with a specific format.
func Tracef(format string, args ...interface{}) {
if !enabled {
return
}
traceLine := getTraceLine()
if traceLine == "" {
return
}
message := fmt.Sprintf(format, args...)
if message != "" {
message = "[" + message + "]"
}
fmt.Fprintln(output, traceLine, message)
}