github.com/mitranim/gg@v0.1.17/log.go (about) 1 package gg 2 3 import ( 4 "fmt" 5 "os" 6 "time" 7 ) 8 9 /* 10 Shortcut for creating `LogTime` with the current time and with a message 11 generated from the inputs via `Str`. 12 */ 13 func LogTimeNow(msg ...any) LogTime { 14 return LogTime{Start: time.Now(), Msg: Str(msg...)} 15 } 16 17 /* 18 Shortcut for logging execution timing to stderr. Usage examples: 19 20 defer gg.LogTimeNow(`some_activity`).LogStart().LogEnd() 21 // perform some activity 22 23 defer gg.LogTimeNow(`some_activity`).LogEnd() 24 // perform some activity 25 26 timer := gg.LogTimeNow(`some_activity`).LogStart() 27 // perform some activity 28 timer.LogEnd() 29 30 timer := gg.LogTimeNow(`some_activity`) 31 // perform some activity 32 timer.LogEnd() 33 */ 34 type LogTime struct { 35 Start time.Time 36 Msg string 37 } 38 39 /* 40 Logs the beginning of the activity denoted by `.Msg`: 41 42 [some_activity] starting 43 */ 44 func (self LogTime) LogStart() LogTime { 45 fmt.Fprintf(os.Stderr, "[%v] starting\n", self.Msg) 46 return self 47 } 48 49 /* 50 Prints the end of the activity denoted by `.Msg`, with time elapsed since the 51 beginning: 52 53 [some_activity] done in <duration> 54 55 If deferred, this will detect the current panic, if any, and print the following 56 instead: 57 58 [some_activity] failed in <duration> 59 */ 60 func (self LogTime) LogEnd() LogTime { 61 since := time.Since(self.Start) 62 err := AnyErrTracedAt(recover(), 1) 63 64 if err != nil { 65 fmt.Fprintf(os.Stderr, "[%v] failed in %v\n", self.Msg, since) 66 panic(err) 67 } 68 69 fmt.Fprintf(os.Stderr, "[%v] done in %v\n", self.Msg, since) 70 return self 71 }