logging_test.go raw

   1  package logging_test
   2  
   3  import (
   4  	"bytes"
   5  	"context"
   6  	"net/http"
   7  	"net/http/httptest"
   8  	"os"
   9  	"path/filepath"
  10  	"strings"
  11  	"syscall"
  12  	"testing"
  13  	"time"
  14  
  15  	"git.smesh.lol/btcd-lite/internal/logging"
  16  )
  17  
  18  // TestLevels: a line below the level is not written, and a line at or above it
  19  // is written with its level in front.
  20  func TestLevels(t *testing.T) {
  21  	var buf bytes.Buffer
  22  	lg := logging.New(&buf, logging.Info)
  23  	lg.Debugf("hidden %d", 1)
  24  	lg.Infof("shown %d", 2)
  25  	lg.Warnf("shown %d", 3)
  26  	lg.Errorf("shown %d", 4)
  27  	out := buf.String()
  28  	if strings.Contains(out, "hidden") {
  29  		t.Fatalf("a debug line was written at info:\n%s", out)
  30  	}
  31  	lg.SetLevel(logging.Debug)
  32  	lg.Debugf("now shown")
  33  	if !strings.Contains(buf.String(), "now shown") {
  34  		t.Fatal("debug was not written after the level was lowered")
  35  	}
  36  	for _, want := range []string{"info: shown 2", "warn: shown 3", "error: shown 4"} {
  37  		if !strings.Contains(out, want) {
  38  			t.Fatalf("%q is not in:\n%s", want, out)
  39  		}
  40  	}
  41  }
  42  
  43  // TestAccessLevels: a success is a debug line, a refusal a warning, a failure
  44  // an error, and a slow success is a line at info.
  45  func TestAccessLevels(t *testing.T) {
  46  	var buf bytes.Buffer
  47  	lg := logging.New(&buf, logging.Info)
  48  	h := lg.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  49  		switch r.URL.Path {
  50  		case "/ok":
  51  			_, _ = w.Write([]byte("hello"))
  52  		case "/no":
  53  			http.Error(w, "nothing covers 1-2", http.StatusNotFound)
  54  		case "/bad":
  55  			http.Error(w, "the file no longer hashes to its name", http.StatusInternalServerError)
  56  		}
  57  	}))
  58  	for _, path := range []string{"/ok", "/no", "/bad"} {
  59  		w := httptest.NewRecorder()
  60  		h.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
  61  	}
  62  	out := buf.String()
  63  	if strings.Contains(out, "path=\"/ok\"") {
  64  		t.Fatalf("a 200 was logged at info:\n%s", out)
  65  	}
  66  	if !strings.Contains(out, "path=\"/no\" status=404") || !strings.Contains(out, `note="nothing covers 1-2`) {
  67  		t.Fatalf("the refusal is not logged with its reason:\n%s", out)
  68  	}
  69  	if !strings.Contains(out, "path=\"/bad\" status=500") || !strings.Contains(out, "note=\"the file no longer hashes") {
  70  		t.Fatalf("the failure is not logged with its reason:\n%s", out)
  71  	}
  72  	st := lg.Stats()
  73  	if st.Requests != 3 || st.Refused != 1 || st.Failed != 1 || st.Bytes == 0 {
  74  		t.Fatalf("stats %+v", st)
  75  	}
  76  	// At debug the success is a line too.
  77  	buf.Reset()
  78  	lg.SetLevel(logging.Debug)
  79  	w := httptest.NewRecorder()
  80  	h.ServeHTTP(w, httptest.NewRequest("GET", "/ok", nil))
  81  	if !strings.Contains(buf.String(), "path=\"/ok\" status=200 bytes=5") {
  82  		t.Fatalf("a 200 was not logged at debug:\n%s", buf.String())
  83  	}
  84  }
  85  
  86  // TestAccessCountsBytes: the byte count is what left the handler, which is what
  87  // an operator adds up to see how much the host uploaded.
  88  func TestAccessCountsBytes(t *testing.T) {
  89  	var buf bytes.Buffer
  90  	lg := logging.New(&buf, logging.Debug)
  91  	body := strings.Repeat("x", 1000)
  92  	h := lg.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  93  		_, _ = w.Write([]byte(body))
  94  	}))
  95  	w := httptest.NewRecorder()
  96  	h.ServeHTTP(w, httptest.NewRequest("GET", "/chunk", nil))
  97  	if got := lg.Stats().Bytes; got != 1000 {
  98  		t.Fatalf("%d bytes counted", got)
  99  	}
 100  	if !strings.Contains(buf.String(), "bytes=1000") {
 101  		t.Fatalf("the line does not carry the count:\n%s", buf.String())
 102  	}
 103  }
 104  
 105  // TestHeartbeat: the line is written on the ticker and stops with the context.
 106  func TestHeartbeat(t *testing.T) {
 107  	var buf bytes.Buffer
 108  	lg := logging.New(&buf, logging.Info)
 109  	ctx, cancel := context.WithCancel(context.Background())
 110  	go lg.Heartbeat(ctx, 10*time.Millisecond, func() string { return "blocks=1" })
 111  	deadline := time.Now().Add(2 * time.Second)
 112  	for !strings.Contains(buf.String(), "heartbeat: blocks=1") {
 113  		if time.Now().After(deadline) {
 114  			t.Fatal("no heartbeat line")
 115  		}
 116  		time.Sleep(5 * time.Millisecond)
 117  	}
 118  	cancel()
 119  	// A zero period writes nothing.
 120  	var quiet bytes.Buffer
 121  	go logging.New(&quiet, logging.Info).Heartbeat(context.Background(), 0, func() string { return "x" })
 122  	time.Sleep(20 * time.Millisecond)
 123  	if quiet.Len() != 0 {
 124  		t.Fatalf("a zero period wrote %q", quiet.String())
 125  	}
 126  }
 127  
 128  // TestReopen: a file destination keeps appending after a reopen, which is what
 129  // a rotation needs.
 130  func TestReopen(t *testing.T) {
 131  	dir := t.TempDir()
 132  	path := filepath.Join(dir, "instance.log")
 133  	lg, err := logging.OpenFile(path, logging.Info)
 134  	if err != nil {
 135  		t.Fatal(err)
 136  	}
 137  	defer lg.Close()
 138  	lg.Infof("before")
 139  	// Rotate: move the file aside and signal.
 140  	if err := os.Rename(path, path+".1"); err != nil {
 141  		t.Fatal(err)
 142  	}
 143  	if err := lg.Reopen(); err != nil {
 144  		t.Fatal(err)
 145  	}
 146  	lg.Infof("after")
 147  	raw, err := os.ReadFile(path)
 148  	if err != nil {
 149  		t.Fatal(err)
 150  	}
 151  	if !strings.Contains(string(raw), "after") || strings.Contains(string(raw), "before") {
 152  		t.Fatalf("the reopened file holds %q", raw)
 153  	}
 154  	old, err := os.ReadFile(path + ".1")
 155  	if err != nil || !strings.Contains(string(old), "before") {
 156  		t.Fatalf("the rotated file holds %q (%v)", old, err)
 157  	}
 158  }
 159  
 160  // TestParseLevel: the flag takes the four names and nothing else.
 161  func TestParseLevel(t *testing.T) {
 162  	for _, name := range []string{"debug", "info", "warn", "error", "INFO", ""} {
 163  		if _, err := logging.ParseLevel(name); err != nil {
 164  			t.Fatalf("%q: %v", name, err)
 165  		}
 166  	}
 167  	if _, err := logging.ParseLevel("verbose"); err == nil {
 168  		t.Fatal("an unknown level was accepted")
 169  	}
 170  }
 171  
 172  // TestSlowSuccessIsALineAtInfo: a request that took longer than the threshold is
 173  // worth a line even though it succeeded, because that is the line that explains
 174  // a client complaining about the server being slow.
 175  func TestSlowSuccessIsALineAtInfo(t *testing.T) {
 176  	var buf bytes.Buffer
 177  	lg := logging.New(&buf, logging.Info)
 178  	lg.Access(logging.Access{
 179  		Remote: "203.0.113.9", Method: "GET", Path: "/v1/chunks/x",
 180  		Status: 200, Bytes: 1 << 20, Dur: 6 * time.Second,
 181  	})
 182  	out := buf.String()
 183  	if !strings.Contains(out, "status=200") || !strings.Contains(out, "slow") {
 184  		t.Fatalf("a slow success is not logged as one:\n%s", out)
 185  	}
 186  	if !strings.Contains(out, "dur_ms=6000") {
 187  		t.Fatalf("the duration is not in the line:\n%s", out)
 188  	}
 189  }
 190  
 191  // TestOffWritesNothing: the off level passes nothing, which is how logging is
 192  // turned off without stopping the process.
 193  func TestOffWritesNothing(t *testing.T) {
 194  	var buf bytes.Buffer
 195  	lg := logging.New(&buf, logging.Off)
 196  	lg.Debugf("d")
 197  	lg.Infof("i")
 198  	lg.Warnf("w")
 199  	lg.Errorf("e")
 200  	if buf.Len() != 0 {
 201  		t.Fatalf("a logger set to off wrote %q", buf.String())
 202  	}
 203  	// And it can be turned back on.
 204  	lg.SetLevel(logging.Info)
 205  	lg.Infof("back")
 206  	if !strings.Contains(buf.String(), "back") {
 207  		t.Fatal("the logger did not write after the level was raised")
 208  	}
 209  	if _, err := logging.ParseLevel("off"); err != nil {
 210  		t.Fatalf("off is not a level name: %v", err)
 211  	}
 212  }
 213  
 214  // TestSignalLevels: SIGUSR1 turns debug on and SIGUSR2 puts it back, which is
 215  // how a process on a host nobody is watching is diagnosed without a restart.
 216  func TestSignalLevels(t *testing.T) {
 217  	var buf bytes.Buffer
 218  	lg := logging.New(&buf, logging.Warn)
 219  	lg.SignalLevels(logging.Warn)
 220  	if got := lg.Level(); got != logging.Warn {
 221  		t.Fatalf("the level started at %s", got)
 222  	}
 223  	if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil {
 224  		t.Fatal(err)
 225  	}
 226  	waitLevel(t, lg, logging.Debug)
 227  	if !strings.Contains(buf.String(), "log level: debug") {
 228  		t.Fatalf("the change was not acknowledged: %q", buf.String())
 229  	}
 230  	if err := syscall.Kill(os.Getpid(), syscall.SIGUSR2); err != nil {
 231  		t.Fatal(err)
 232  	}
 233  	waitLevel(t, lg, logging.Warn)
 234  	if !strings.Contains(buf.String(), "log level: warn") {
 235  		t.Fatalf("the reset was not acknowledged: %q", buf.String())
 236  	}
 237  }
 238  
 239  // waitLevel waits for a signal handler to move the level, which is asynchronous
 240  // on purpose.
 241  func waitLevel(t *testing.T, lg *logging.Logger, want logging.Level) {
 242  	t.Helper()
 243  	deadline := time.Now().Add(2 * time.Second)
 244  	for lg.Level() != want {
 245  		if time.Now().After(deadline) {
 246  			t.Fatalf("the level is %s, want %s", lg.Level(), want)
 247  		}
 248  		time.Sleep(2 * time.Millisecond)
 249  	}
 250  }
 251