Skip to content

Commit 913568f

Browse files
committed
added timeNow override
1 parent 970db52 commit 913568f

File tree

4 files changed

+39
-2
lines changed

4 files changed

+39
-2
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
*.test
2+
.idea
3+
*.iml
4+
*~

example_test.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package logging
22

3-
import "os"
3+
import (
4+
"os"
5+
"time"
6+
)
47

58
func Example() {
69
// This call is for testing purposes and will set the time to unix epoch.
@@ -27,6 +30,11 @@ func Example() {
2730
backend2Leveled := AddModuleLevel(backend2Formatter)
2831
backend2Leveled.SetLevel(ERROR, "")
2932

33+
// Log UTC time, default is Local
34+
SetTimeNow(func() time.Time {
35+
return time.Now().UTC()
36+
})
37+
3038
// Set the backends to be used and the default level.
3139
SetBackend(backend1, backend2Leveled)
3240

logger.go

+5
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ func MustGetLogger(module string) *Logger {
123123
return logger
124124
}
125125

126+
// SetTimeNow configures the time.Time value generated for log time values
127+
func SetTimeNow(now func () time.Time) {
128+
timeNow = now
129+
}
130+
126131
// Reset restores the internal state of the logging library.
127132
func Reset() {
128133
// TODO make a global Init() method to be less magic? or make it such that

logger_test.go

+21-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
package logging
66

7-
import "testing"
7+
import (
8+
"testing"
9+
"time"
10+
)
811

912
type Password string
1013

@@ -60,3 +63,20 @@ func TestPrivateBackend(t *testing.T) {
6063
t.Error("logged to defaultBackend:", MemoryRecordN(privateBackend, 0))
6164
}
6265
}
66+
67+
func TestLogger_SetTimerNow(t *testing.T) {
68+
_ = InitForTesting(DEBUG)
69+
_ = MustGetLogger("test")
70+
71+
if now := timeNow(); now != time.Unix(0, 0).UTC() {
72+
t.Error("test timeNow incorrect", now)
73+
}
74+
75+
SetTimeNow(func() time.Time {
76+
return time.Unix(1, 1)
77+
})
78+
79+
if now := timeNow(); now != time.Unix(1, 1) {
80+
t.Error("test timeNow dit not get overwritten", now)
81+
}
82+
}

0 commit comments

Comments
 (0)