|
| 1 | +package log |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "os" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +// TestLoggingWithTrace checks that if BackTraceAt is set, then the |
| 11 | +// gloghandler is capable of spitting out a stacktrace |
| 12 | +func TestLoggingWithTrace(t *testing.T) { |
| 13 | + defer stackEnabled.Store(stackEnabled.Load()) |
| 14 | + out := new(bytes.Buffer) |
| 15 | + logger := New() |
| 16 | + { |
| 17 | + glog := NewGlogHandler(StreamHandler(out, TerminalFormat(false))) |
| 18 | + glog.Verbosity(LvlTrace) |
| 19 | + if err := glog.BacktraceAt("logger_test.go:24"); err != nil { |
| 20 | + t.Fatal(err) |
| 21 | + } |
| 22 | + logger.SetHandler(glog) |
| 23 | + } |
| 24 | + logger.Trace("a message", "foo", "bar") // Will be bumped to INFO |
| 25 | + have := out.String() |
| 26 | + if !strings.HasPrefix(have, "INFO") { |
| 27 | + t.Fatalf("backtraceat should bump level to info: %s", have) |
| 28 | + } |
| 29 | + // The timestamp is locale-dependent, so we want to trim that off |
| 30 | + // "INFO [01-01|00:00:00.000] a messag ..." -> "a messag..." |
| 31 | + have = strings.Split(have, "]")[1] |
| 32 | + wantPrefix := " a message\n\ngoroutine" |
| 33 | + if !strings.HasPrefix(have, wantPrefix) { |
| 34 | + t.Errorf("\nhave: %q\nwant: %q\n", have, wantPrefix) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// TestLoggingWithVmodule checks that vmodule works. |
| 39 | +func TestLoggingWithVmodule(t *testing.T) { |
| 40 | + defer stackEnabled.Store(stackEnabled.Load()) |
| 41 | + out := new(bytes.Buffer) |
| 42 | + logger := New() |
| 43 | + { |
| 44 | + glog := NewGlogHandler(StreamHandler(out, TerminalFormat(false))) |
| 45 | + glog.Verbosity(LvlCrit) |
| 46 | + logger.SetHandler(glog) |
| 47 | + logger.Warn("This should not be seen", "ignored", "true") |
| 48 | + glog.Vmodule("logger_test.go=5") |
| 49 | + } |
| 50 | + logger.Trace("a message", "foo", "bar") |
| 51 | + have := out.String() |
| 52 | + // The timestamp is locale-dependent, so we want to trim that off |
| 53 | + // "INFO [01-01|00:00:00.000] a messag ..." -> "a messag..." |
| 54 | + have = strings.Split(have, "]")[1] |
| 55 | + want := " a message foo=bar\n" |
| 56 | + if have != want { |
| 57 | + t.Errorf("\nhave: %q\nwant: %q\n", have, want) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func BenchmarkTraceLogging(b *testing.B) { |
| 62 | + Root().SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(os.Stderr, TerminalFormat(true)))) |
| 63 | + b.ResetTimer() |
| 64 | + for i := 0; i < b.N; i++ { |
| 65 | + Trace("a message", "v", i) |
| 66 | + } |
| 67 | +} |
0 commit comments