-
Notifications
You must be signed in to change notification settings - Fork 23
/
handler_timed_rotating_file_test.go
74 lines (69 loc) · 1.76 KB
/
handler_timed_rotating_file_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
package logging
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/hhkbp2/go-strftime"
"github.com/hhkbp2/testify/require"
)
func cleanupLogFils(t *testing.T, basepath string) int {
dirName, baseName := filepath.Split(basepath)
fileInfos, err := ioutil.ReadDir(dirName)
require.Nil(t, err)
count := 0
for _, info := range fileInfos {
name := info.Name()
if strings.HasPrefix(name, baseName) {
require.Nil(t, os.Remove(filepath.Join(dirName, name)))
count += 1
}
}
return count
}
func checkFileContent(t *testing.T, file, content string) {
c, err := ioutil.ReadFile(file)
require.Nil(t, err)
require.Equal(t, content, string(c))
}
func TestTimedRotatingFileHandler_WithBackup(t *testing.T) {
defer Shutdown()
cleanupLogFils(t, testFileName)
when := "S"
format := "%Y-%m-%d_%H-%M-%S"
interval := 2
handler, err := NewTimedRotatingFileHandler(
testFileName,
testFileMode,
testBufferSize,
testBufferFlushTime,
testInputChanSize,
when,
uint32(interval),
testRotateBackupCount,
false)
require.Nil(t, err)
logger := GetLogger("trfile")
logger.AddHandler(handler)
message := "test"
lastMessage := "last message"
times := make([]time.Time, 0, testRotateBackupCount)
for i := uint32(0); i < testRotateBackupCount+1; i++ {
logger.Errorf(message)
if i > 0 {
times = append(times, time.Now())
}
time.Sleep(time.Duration(int64(time.Second) * int64(interval)))
}
logger.Errorf(lastMessage)
logger.RemoveHandler(handler)
handler.Close()
for i := uint32(0); i < testRotateBackupCount; i++ {
suffix := strftime.Format(format, times[i])
checkFileContent(t, testFileName+"."+suffix, message+"\n")
}
checkFileContent(t, testFileName, lastMessage+"\n")
require.Equal(t, 2, cleanupLogFils(t, testFileName))
}