Skip to content

Commit 61e4ad6

Browse files
committed
feat: improve ExecuteTime log formatting and add output test
- Change log output in ExecuteTime to display the title first and elapsed time in milliseconds - Add a unit test for ExecuteTime to verify the log output format Signed-off-by: Bo-Yi Wu <[email protected]>
1 parent 8bfbcc6 commit 61e4ad6

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

trace/trace.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ func ExecuteTime(title string, fn func()) {
99
start := time.Now()
1010
fn()
1111
elapsed := time.Since(start)
12-
log.Printf("[%s] %s", elapsed, title)
12+
log.Printf("[%s] elapsed=%dms", title, elapsed.Milliseconds())
1313
}

trace/trace_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package trace
22

33
import (
4+
"bytes"
5+
"log"
6+
"strings"
7+
"testing"
48
"time"
59
)
610

@@ -19,3 +23,19 @@ func ExampleExecuteTime() {
1923

2024
// Output:
2125
}
26+
27+
func TestExecuteTime(t *testing.T) {
28+
var buf bytes.Buffer
29+
orig := log.Writer()
30+
log.SetOutput(&buf)
31+
defer log.SetOutput(orig)
32+
33+
ExecuteTime("unit test", func() {
34+
time.Sleep(10 * time.Millisecond)
35+
})
36+
37+
out := buf.String()
38+
if !strings.Contains(out, "[unit test] elapsed=") || !strings.Contains(out, "ms") {
39+
t.Errorf("log output format incorrect: %q", out)
40+
}
41+
}

0 commit comments

Comments
 (0)