github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/console_test.go (about) 1 package tlog 2 3 import ( 4 "io" 5 "testing" 6 "time" 7 8 "github.com/nikandfor/assert" 9 "github.com/nikandfor/loc" 10 11 "github.com/nikandfor/tlog/low" 12 "github.com/nikandfor/tlog/tlwire" 13 ) 14 15 type TeeWriter []io.Writer 16 17 func TestConsoleLocations(t *testing.T) { 18 var buf, raw low.Buf 19 20 w := NewConsoleWriter(&buf, 0) 21 l := New(TeeWriter{&raw, w}) 22 23 w.PadEmptyMessage = false 24 25 c := loc.Caller(-1) 26 cc := loc.Callers(-1, 2) 27 28 { 29 name, file, line := c.NameFileLine() 30 t.Logf("caller: %v %v %v", name, file, line) 31 32 for _, pc := range cc { 33 name, file, line := pc.NameFileLine() 34 t.Logf("callers: %v %v %v", name, file, line) 35 } 36 } 37 38 _ = l.Event("caller", c) 39 assert.Equal(t, "caller=location.go:24\n", string(buf)) 40 41 buf = buf[:0] 42 43 _ = l.Event("callers", cc) 44 assert.Equal(t, "callers=[location.go:71 console_test.go:26]\n", string(buf)) 45 46 t.Logf("dump:\n%v", tlwire.Dump(raw)) 47 } 48 49 func (w TeeWriter) Write(p []byte) (n int, err error) { 50 for i, w := range w { 51 m, e := w.Write(p) 52 53 if i == 0 { 54 n = m 55 } 56 57 if err == nil { 58 err = e 59 } 60 } 61 62 return 63 } 64 65 func TestAppendDuration(t *testing.T) { 66 w := NewConsoleWriter(nil, 0) 67 68 t.Logf("%s", w.AppendDuration(nil, 0)) 69 70 for _, days := range []int{0, 2} { 71 for _, h := range []int{0, 12} { 72 for _, m := range []int{0, 2} { 73 for _, s := range []int{0, 36} { 74 d := time.Hour*time.Duration(24*days+h) + 75 time.Minute*time.Duration(m) + 76 time.Second*time.Duration(s) 77 78 t.Logf("%s is %v", w.AppendDuration(nil, d), d) 79 } 80 } 81 } 82 } 83 84 for d := time.Nanosecond; d < 100*time.Second; d *= 7 { 85 t.Logf("%s is %v", w.AppendDuration(nil, d), d) 86 } 87 88 for f := float64(1); f < float64(200*time.Microsecond); f *= 1.378 { 89 d := time.Duration(f) 90 t.Logf("%s is %v", w.AppendDuration(nil, d), d) 91 } 92 93 d := 99999 * time.Microsecond 94 t.Logf("%s is %v", w.AppendDuration(nil, d), d) 95 d = 999999 * time.Microsecond 96 t.Logf("%s is %v", w.AppendDuration(nil, d), d) 97 } 98 99 func BenchmarkConsolePrintw(b *testing.B) { 100 b.ReportAllocs() 101 102 w := NewConsoleWriter(io.Discard, LdetFlags) 103 l := New(w) 104 105 for i := 0; i < b.N; i++ { 106 l.Printw("message", "a", i+1000, "b", i+1000, "c", "str") 107 } 108 } 109 110 func BenchmarkConsoleStartPrintwFinish(b *testing.B) { 111 b.ReportAllocs() 112 113 w := NewConsoleWriter(io.Discard, LdetFlags) 114 l := New(w) 115 116 for i := 0; i < b.N; i++ { 117 tr := l.Start("span_name") 118 tr.Printw("message", "a", i+1000, "b", i+1000, "c", "str") 119 tr.Finish() 120 } 121 }