-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathtest.go
72 lines (63 loc) · 2.16 KB
/
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
/*
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package log
import (
"sync"
"time"
)
// test implements a logger than can be passed a testing.T (which will only output logs for failed tests)
// testLogger contains the logging functions provided by testing.T
type testLogger interface {
Log(args ...interface{})
Logf(format string, args ...interface{})
}
// The TestLog type is an adapter to allow the use of testing.T as a paho.Logger.
// With this implementation, log messages will only be output when a test fails (and will be associated with the test).
type TestLog struct {
sync.Mutex
l testLogger
prefix string
}
// NewTestLogger accepts a testLogger (e.g. Testing.T) and a prefix (added to messages logged) and returns a Logger
func NewTestLogger(l testLogger, prefix string) *TestLog {
return &TestLog{
l: l,
prefix: prefix,
}
}
// Println prints a line to the log
// Println its arguments in the test log (only printed if the test files or appropriate arguments passed to go test).
func (t *TestLog) Println(v ...interface{}) {
t.Lock()
defer t.Unlock()
if t.l != nil {
t.l.Log(append([]interface{}{time.Now().Format(time.RFC3339Nano), t.prefix}, v...)...)
}
}
// Printf formats its arguments according to the format, analogous to fmt.Printf, and
// records the text in the test log (only printed if the test files or appropriate arguments passed to go test).
func (t *TestLog) Printf(format string, v ...interface{}) {
t.Lock()
defer t.Unlock()
if t.l != nil {
t.l.Logf(time.Now().Format(time.RFC3339Nano)+" "+t.prefix+format, v...)
}
}
// Stop prevents future logging
// func (t *TestLog) Stop() {
// t.Lock()
// defer t.Unlock()
// t.l = nil
// }