package logshipper import ( "bytes" "log" "net/http" "regexp" "strings" "testing" "time" ) var timestampPattern = regexp.MustCompile(`\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} `) // The console output must match what the standard log package writes with the same flags and prefix. func TestLoggerConsoleOutputMatchesTheStandardLogger(t *testing.T) { oldFlags, oldPrefix := log.Flags(), log.Prefix() log.SetFlags(log.LstdFlags) log.SetPrefix("svc: ") defer log.SetFlags(oldFlags) defer log.SetPrefix(oldPrefix) var console, reference bytes.Buffer logger := NewLogger(&console, nil) logger.Infof("started on %s", ":8080") logger.Errorf("push failed: %v", "boom") std := log.New(&reference, log.Prefix(), log.Flags()) std.Printf("started on %s", ":8080") std.Printf("push failed: %v", "boom") stripTimes := func(s string) string { return timestampPattern.ReplaceAllString(s, "") } if stripTimes(console.String()) != stripTimes(reference.String()) { t.Fatalf("console = %q, want the standard logger's %q (apart from timestamps)", console.String(), reference.String()) } } // Each method ships at its own severity, and nothing reaches the console twice. func TestLoggerShipsEachLineAtItsSeverityOnce(t *testing.T) { in := newIngest(t, http.StatusAccepted) shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "debug"}) defer shipper.Close() var console bytes.Buffer logger := NewLogger(&console, shipper) logger.Debugf("d") logger.Infof("i") logger.Warnf("w") logger.Errorf("e") logger.Criticalf("c") shipper.Flush() if n := strings.Count(console.String(), "\n"); n != 5 { t.Fatalf("console got %d lines, want 5: %q", n, console.String()) } entries := in.entries() want := map[string]string{"d": "debug", "i": "info", "w": "warn", "e": "error", "c": "critical"} if len(entries) != len(want) { t.Fatalf("shipped %d entries, want %d: %+v", len(entries), len(want), entries) } for _, e := range entries { if want[e.Message] != e.Level { t.Errorf("%q shipped at %q, want %q", e.Message, e.Level, want[e.Message]) } } } // A nil shipper keeps the Logger console-only, and the threshold still applies to what is shipped. func TestLoggerWithoutShipperIsConsoleOnlyAndThresholdApplies(t *testing.T) { var console bytes.Buffer NewLogger(&console, nil).Debugf("still printed") if !strings.Contains(console.String(), "still printed") { t.Fatalf("console-only logger dropped a line: %q", console.String()) } in := newIngest(t, http.StatusAccepted) shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"}) defer shipper.Close() NewLogger(&bytes.Buffer{}, shipper).Warnf("below threshold") shipper.Flush() time.Sleep(10 * time.Millisecond) if n := len(in.entries()); n != 0 { t.Fatalf("shipped %d entries below the threshold", n) } }