-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotoslog_test.go
88 lines (79 loc) · 1.94 KB
/
rotoslog_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2023 Filippo Veneri. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package rotoslog
import (
"bytes"
"fmt"
"log/slog"
"os"
"strings"
"testing"
)
func init() {
os.RemoveAll(defaultConfig.logDir)
}
func countLinesInFile(filename string) (int, error) {
lineSep := []byte{'\n'}
buf, err := os.ReadFile(filename)
if err != nil {
return 0, err
}
return bytes.Count(buf, lineSep), nil
}
const (
EXPECTED_NUMBER_OF_FILES = 3
EXPECTED_LINE_NUMBER = 32
)
func checkResults(h handler) error {
entries, err := os.ReadDir(h.cnf.logDir)
if err != nil {
return err
}
var n uint64
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), h.cnf.filePrefix) {
continue
}
n++
path := h.cnf.filePath(entry.Name())
l, err := countLinesInFile(path)
if err != nil {
return err
}
if l != EXPECTED_LINE_NUMBER {
return fmt.Errorf("%s has the wrong number of lines: got %d, expected %d", path, l, EXPECTED_LINE_NUMBER)
}
}
if n != EXPECTED_NUMBER_OF_FILES {
return fmt.Errorf("wrong number of log files, got %d, expected %d", n, EXPECTED_NUMBER_OF_FILES)
}
return nil
}
func TestHandler(t *testing.T) {
h, err := NewHandler(
FilePrefix("test-"),
CurrentFileSuffix("active"),
FileExt(".txt"),
DateTimeLayout("20060102150405.000000000"),
MaxFileSize(2048),
HandlerOptions(slog.HandlerOptions{Level: slog.LevelDebug}),
MaxRotatedFiles(EXPECTED_NUMBER_OF_FILES-1),
LogHandlerBuilder(slog.NewTextHandler),
)
if err != nil {
t.Fatal(err)
}
logger := slog.New(h)
n := (EXPECTED_NUMBER_OF_FILES + 1) * 32 / 4
for i := 0; i < n; i++ {
logger.Debug("dbg msg", "i", i)
logger.Info("nfo msg", "i", i)
logger.Warn("wrn msg", "i", i)
logger.Error("err msg", "i", i)
}
err = checkResults(h.(handler))
if err != nil {
t.Fatal(err)
}
}