-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
71 lines (56 loc) · 1.43 KB
/
log.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
package gg
import (
"fmt"
"os"
"time"
)
/*
Shortcut for creating `LogTime` with the current time and with a message
generated from the inputs via `Str`.
*/
func LogTimeNow(msg ...any) LogTime {
return LogTime{Start: time.Now(), Msg: Str(msg...)}
}
/*
Shortcut for logging execution timing to stderr. Usage examples:
defer gg.LogTimeNow(`some_activity`).LogStart().LogEnd()
// perform some activity
defer gg.LogTimeNow(`some_activity`).LogEnd()
// perform some activity
timer := gg.LogTimeNow(`some_activity`).LogStart()
// perform some activity
timer.LogEnd()
timer := gg.LogTimeNow(`some_activity`)
// perform some activity
timer.LogEnd()
*/
type LogTime struct {
Start time.Time
Msg string
}
/*
Logs the beginning of the activity denoted by `.Msg`:
[some_activity] starting
*/
func (self LogTime) LogStart() LogTime {
fmt.Fprintf(os.Stderr, "[%v] starting\n", self.Msg)
return self
}
/*
Prints the end of the activity denoted by `.Msg`, with time elapsed since the
beginning:
[some_activity] done in <duration>
If deferred, this will detect the current panic, if any, and print the following
instead:
[some_activity] failed in <duration>
*/
func (self LogTime) LogEnd() LogTime {
since := time.Since(self.Start)
err := AnyErrTracedAt(recover(), 1)
if err != nil {
fmt.Fprintf(os.Stderr, "[%v] failed in %v\n", self.Msg, since)
panic(err)
}
fmt.Fprintf(os.Stderr, "[%v] done in %v\n", self.Msg, since)
return self
}