Skip to content

Commit 8da9a83

Browse files
committed
test and protect edge case
1 parent 9c5ba74 commit 8da9a83

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

database/slowlog.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ func NewSlowLogger(maxEntries int, threshold int64) *SlowLogger {
4242
}
4343

4444
func (sl *SlowLogger) Record(start time.Time, args [][]byte, client string) {
45+
if sl == nil || len(sl.entries) == 0 {
46+
return
47+
}
4548
duration := time.Since(start)
4649
micros := duration.Microseconds()
4750

database/slowlog_test.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,26 @@ import (
1212
func TestSlowLogger_Record(t *testing.T) {
1313
logger := NewSlowLogger(5, 1000)
1414

15-
start := time.Now()
16-
time.Sleep(2 * time.Millisecond)
17-
18-
logger.Record(start, utils.ToCmdLine("GET", "key1"), "127.0.0.1:12345")
15+
start := time.Now().Add(-time.Minute)
16+
for i := 0; i < 10; i++ {
17+
logger.Record(start, utils.ToCmdLine("GET", strconv.Itoa(i)), "127.0.0.1:12345")
18+
}
1919

20-
if logger.Len() != 1 {
20+
if logger.Len() != 5 {
2121
t.Errorf("Expected 1 entry, got %d", logger.Len())
2222
}
23+
for i, e := range logger.entries {
24+
actual := string(e.Command[1])
25+
expect := strconv.Itoa(i+5)
26+
if actual != expect {
27+
t.Errorf("Expected %s, got %s", expect, actual)
28+
}
29+
}
2330

31+
logger2 := NewSlowLogger(5, 1000)
2432
start = time.Now()
25-
logger.Record(start, utils.ToCmdLine("SET", "key2"), "127.0.0.1:12346")
26-
if logger.Len() != 1 {
33+
logger2.Record(start, utils.ToCmdLine("SET", "key2"), "127.0.0.1:12346")
34+
if logger2.Len() != 0 {
2735
t.Errorf("Below threshold query should not be recorded, got %d entries", logger.Len())
2836
}
2937
}

0 commit comments

Comments
 (0)