-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.go
More file actions
64 lines (57 loc) · 1.5 KB
/
debug.go
File metadata and controls
64 lines (57 loc) · 1.5 KB
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
package main
import (
"fmt"
"os"
"path/filepath"
"sync"
"time"
)
// debugLog is a timestamped append-only debug log for trupal internals.
// Written to .trupal.debug in the project directory.
var debugLog struct {
mu sync.Mutex
file *os.File
}
// InitDebugLog opens the debug log file. Call once at startup.
func InitDebugLog(projectDir string) {
path := filepath.Join(projectDir, ".trupal.debug")
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return
}
debugLog.file = f
Debugf("trupal debug log started for %s", projectDir)
}
// CloseDebugLog closes the debug log file.
func CloseDebugLog() {
debugLog.mu.Lock()
defer debugLog.mu.Unlock()
if debugLog.file != nil {
debugLog.file.Close()
}
}
func DebugEnabled() bool {
return debugLog.file != nil
}
func RotateDebugLog(projectDir string) {
debugLog.mu.Lock()
defer debugLog.mu.Unlock()
if debugLog.file != nil {
debugLog.file.Close()
}
os.Rename(filepath.Join(projectDir, ".trupal.debug"), filepath.Join(projectDir, ".trupal.debug.old"))
f, _ := os.OpenFile(filepath.Join(projectDir, ".trupal.debug"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
debugLog.file = f
}
// Debugf writes a timestamped line to the debug log.
func Debugf(format string, args ...interface{}) {
debugLog.mu.Lock()
defer debugLog.mu.Unlock()
if debugLog.file == nil {
return
}
ts := time.Now().Format("15:04:05.000")
msg := fmt.Sprintf(format, args...)
fmt.Fprintf(debugLog.file, "%s %s\n", ts, msg)
debugLog.file.Sync()
}