-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystem_logging.go
113 lines (94 loc) · 2.18 KB
/
system_logging.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
package spin
import (
"fmt"
"log"
"os"
"runtime/pprof"
"time"
"github.com/drop-target-pinball/spin/rlog"
)
const (
DebugStackTrace = "StackTrace"
)
var (
logger *rlog.Logger // FIXME: This should be in the Engine
)
func init() {
logger = rlog.New(60*time.Second, log.Default())
}
type loggingSystem struct {
startTime time.Time
}
func RegisterLoggingSystem(eng *Engine) {
sys := &loggingSystem{
startTime: time.Now(),
}
eng.RegisterActionHandler(sys)
eng.RegisterEventHandler(sys)
}
func (s *loggingSystem) HandleAction(action Action) {
log.Printf("[%v] %v", s.elapsedTime(), FormatAction(action))
switch act := action.(type) {
case Debug:
s.debug(act)
}
}
func (s *loggingSystem) HandleEvent(evt Event) {
logger.Printf("[%v] %v", s.elapsedTime(), FormatEvent(evt))
// FIXME: this is a hack
sw, ok := evt.(SwitchEvent)
if ok {
if sw.ID == "jd.SwitchBuyInButton" {
dumpLog()
}
}
}
func (s *loggingSystem) debug(act Debug) {
switch act.ID {
case DebugStackTrace:
debugStackTrace()
}
}
func (s *loggingSystem) elapsedTime() string {
now := time.Now()
diff := float64(now.Sub(s.startTime).Milliseconds()) / 1000
return fmt.Sprintf("%10.3f", diff)
}
func Error(format string, a ...interface{}) {
format = "(*) " + format
logger.Printf(format, a...)
}
func Warn(format string, a ...interface{}) {
format = "(!) " + format
logger.Printf(format, a...)
}
func Info(format string, a ...interface{}) {
format = "(?) " + format
logger.Printf(format, a...)
}
func Log(format string, a ...interface{}) {
logger.Printf(format, a...)
}
func debugStackTrace() {
profile := pprof.Lookup("goroutine")
profile.WriteTo(os.Stdout, 1)
}
func dumpLog() {
timestamp := time.Now().Format("060102-130405")
dir := os.Getenv("SPIN_DIR") + "/log"
if err := os.MkdirAll(dir, 0o755); err != nil {
Error("unable to create directory %v: %v", dir, err)
}
file := dir + "/spin-" + timestamp + ".log"
Log("writing log to file %v", file)
f, err := os.Create(file)
if err != nil {
Error("unable to create file %v: %v", file, err)
}
defer f.Close()
for _, message := range logger.Messages() {
f.WriteString(message + "\n")
}
profile := pprof.Lookup("goroutine")
profile.WriteTo(f, 1)
}