package logging_test import ( "bytes" "context" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "syscall" "testing" "time" "git.smesh.lol/btcd-lite/internal/logging" ) // TestLevels: a line below the level is not written, and a line at or above it // is written with its level in front. func TestLevels(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Info) lg.Debugf("hidden %d", 1) lg.Infof("shown %d", 2) lg.Warnf("shown %d", 3) lg.Errorf("shown %d", 4) out := buf.String() if strings.Contains(out, "hidden") { t.Fatalf("a debug line was written at info:\n%s", out) } lg.SetLevel(logging.Debug) lg.Debugf("now shown") if !strings.Contains(buf.String(), "now shown") { t.Fatal("debug was not written after the level was lowered") } for _, want := range []string{"info: shown 2", "warn: shown 3", "error: shown 4"} { if !strings.Contains(out, want) { t.Fatalf("%q is not in:\n%s", want, out) } } } // TestAccessLevels: a success is a debug line, a refusal a warning, a failure // an error, and a slow success is a line at info. func TestAccessLevels(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Info) h := lg.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/ok": _, _ = w.Write([]byte("hello")) case "/no": http.Error(w, "nothing covers 1-2", http.StatusNotFound) case "/bad": http.Error(w, "the file no longer hashes to its name", http.StatusInternalServerError) } })) for _, path := range []string{"/ok", "/no", "/bad"} { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) } out := buf.String() if strings.Contains(out, "path=\"/ok\"") { t.Fatalf("a 200 was logged at info:\n%s", out) } if !strings.Contains(out, "path=\"/no\" status=404") || !strings.Contains(out, `note="nothing covers 1-2`) { t.Fatalf("the refusal is not logged with its reason:\n%s", out) } if !strings.Contains(out, "path=\"/bad\" status=500") || !strings.Contains(out, "note=\"the file no longer hashes") { t.Fatalf("the failure is not logged with its reason:\n%s", out) } st := lg.Stats() if st.Requests != 3 || st.Refused != 1 || st.Failed != 1 || st.Bytes == 0 { t.Fatalf("stats %+v", st) } // At debug the success is a line too. buf.Reset() lg.SetLevel(logging.Debug) w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", "/ok", nil)) if !strings.Contains(buf.String(), "path=\"/ok\" status=200 bytes=5") { t.Fatalf("a 200 was not logged at debug:\n%s", buf.String()) } } // TestAccessCountsBytes: the byte count is what left the handler, which is what // an operator adds up to see how much the host uploaded. func TestAccessCountsBytes(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Debug) body := strings.Repeat("x", 1000) h := lg.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) })) w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", "/chunk", nil)) if got := lg.Stats().Bytes; got != 1000 { t.Fatalf("%d bytes counted", got) } if !strings.Contains(buf.String(), "bytes=1000") { t.Fatalf("the line does not carry the count:\n%s", buf.String()) } } // TestHeartbeat: the line is written on the ticker and stops with the context. func TestHeartbeat(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Info) ctx, cancel := context.WithCancel(context.Background()) go lg.Heartbeat(ctx, 10*time.Millisecond, func() string { return "blocks=1" }) deadline := time.Now().Add(2 * time.Second) for !strings.Contains(buf.String(), "heartbeat: blocks=1") { if time.Now().After(deadline) { t.Fatal("no heartbeat line") } time.Sleep(5 * time.Millisecond) } cancel() // A zero period writes nothing. var quiet bytes.Buffer go logging.New(&quiet, logging.Info).Heartbeat(context.Background(), 0, func() string { return "x" }) time.Sleep(20 * time.Millisecond) if quiet.Len() != 0 { t.Fatalf("a zero period wrote %q", quiet.String()) } } // TestReopen: a file destination keeps appending after a reopen, which is what // a rotation needs. func TestReopen(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "instance.log") lg, err := logging.OpenFile(path, logging.Info) if err != nil { t.Fatal(err) } defer lg.Close() lg.Infof("before") // Rotate: move the file aside and signal. if err := os.Rename(path, path+".1"); err != nil { t.Fatal(err) } if err := lg.Reopen(); err != nil { t.Fatal(err) } lg.Infof("after") raw, err := os.ReadFile(path) if err != nil { t.Fatal(err) } if !strings.Contains(string(raw), "after") || strings.Contains(string(raw), "before") { t.Fatalf("the reopened file holds %q", raw) } old, err := os.ReadFile(path + ".1") if err != nil || !strings.Contains(string(old), "before") { t.Fatalf("the rotated file holds %q (%v)", old, err) } } // TestParseLevel: the flag takes the four names and nothing else. func TestParseLevel(t *testing.T) { for _, name := range []string{"debug", "info", "warn", "error", "INFO", ""} { if _, err := logging.ParseLevel(name); err != nil { t.Fatalf("%q: %v", name, err) } } if _, err := logging.ParseLevel("verbose"); err == nil { t.Fatal("an unknown level was accepted") } } // TestSlowSuccessIsALineAtInfo: a request that took longer than the threshold is // worth a line even though it succeeded, because that is the line that explains // a client complaining about the server being slow. func TestSlowSuccessIsALineAtInfo(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Info) lg.Access(logging.Access{ Remote: "203.0.113.9", Method: "GET", Path: "/v1/chunks/x", Status: 200, Bytes: 1 << 20, Dur: 6 * time.Second, }) out := buf.String() if !strings.Contains(out, "status=200") || !strings.Contains(out, "slow") { t.Fatalf("a slow success is not logged as one:\n%s", out) } if !strings.Contains(out, "dur_ms=6000") { t.Fatalf("the duration is not in the line:\n%s", out) } } // TestOffWritesNothing: the off level passes nothing, which is how logging is // turned off without stopping the process. func TestOffWritesNothing(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Off) lg.Debugf("d") lg.Infof("i") lg.Warnf("w") lg.Errorf("e") if buf.Len() != 0 { t.Fatalf("a logger set to off wrote %q", buf.String()) } // And it can be turned back on. lg.SetLevel(logging.Info) lg.Infof("back") if !strings.Contains(buf.String(), "back") { t.Fatal("the logger did not write after the level was raised") } if _, err := logging.ParseLevel("off"); err != nil { t.Fatalf("off is not a level name: %v", err) } } // TestSignalLevels: SIGUSR1 turns debug on and SIGUSR2 puts it back, which is // how a process on a host nobody is watching is diagnosed without a restart. func TestSignalLevels(t *testing.T) { var buf bytes.Buffer lg := logging.New(&buf, logging.Warn) lg.SignalLevels(logging.Warn) if got := lg.Level(); got != logging.Warn { t.Fatalf("the level started at %s", got) } if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil { t.Fatal(err) } waitLevel(t, lg, logging.Debug) if !strings.Contains(buf.String(), "log level: debug") { t.Fatalf("the change was not acknowledged: %q", buf.String()) } if err := syscall.Kill(os.Getpid(), syscall.SIGUSR2); err != nil { t.Fatal(err) } waitLevel(t, lg, logging.Warn) if !strings.Contains(buf.String(), "log level: warn") { t.Fatalf("the reset was not acknowledged: %q", buf.String()) } } // waitLevel waits for a signal handler to move the level, which is asynchronous // on purpose. func waitLevel(t *testing.T, lg *logging.Logger, want logging.Level) { t.Helper() deadline := time.Now().Add(2 * time.Second) for lg.Level() != want { if time.Now().After(deadline) { t.Fatalf("the level is %s, want %s", lg.Level(), want) } time.Sleep(2 * time.Millisecond) } }