| 1 |
/* |
| 2 |
* Copyright (c) 2024 Contributors to the Eclipse Foundation |
| 3 |
* |
| 4 |
* All rights reserved. This program and the accompanying materials |
| 5 |
* are made available under the terms of the Eclipse Public License v2.0 |
| 6 |
* and Eclipse Distribution License v1.0 which accompany this distribution. |
| 7 |
* |
| 8 |
* The Eclipse Public License is available at |
| 9 |
* https://www.eclipse.org/legal/epl-2.0/ |
| 10 |
* and the Eclipse Distribution License is available at |
| 11 |
* http://www.eclipse.org/org/documents/edl-v10.php. |
| 12 |
* |
| 13 |
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause |
| 14 |
*/ |
| 15 |
|
| 16 |
package log |
| 17 |
|
| 18 |
import ( |
| 19 |
"sync" |
| 20 |
"time" |
| 21 |
) |
| 22 |
|
| 23 |
// test implements a logger than can be passed a testing.T (which will only output logs for failed tests) |
| 24 |
|
| 25 |
// testLogger contains the logging functions provided by testing.T |
| 26 |
type testLogger interface { |
| 27 |
Log(args ...interface{}) |
| 28 |
Logf(format string, args ...interface{}) |
| 29 |
} |
| 30 |
|
| 31 |
// The TestLog type is an adapter to allow the use of testing.T as a paho.Logger. |
| 32 |
// With this implementation, log messages will only be output when a test fails (and will be associated with the test). |
| 33 |
type TestLog struct { |
| 34 |
sync.Mutex |
| 35 |
l testLogger |
| 36 |
prefix string |
| 37 |
} |
| 38 |
|
| 39 |
// NewTestLogger accepts a testLogger (e.g. Testing.T) and a prefix (added to messages logged) and returns a Logger |
| 40 |
func NewTestLogger(l testLogger, prefix string) *TestLog { |
| 41 |
return &TestLog{ |
| 42 |
l: l, |
| 43 |
prefix: prefix, |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
// Println prints a line to the log |
| 48 |
// Println its arguments in the test log (only printed if the test files or appropriate arguments passed to go test). |
| 49 |
func (t *TestLog) Println(v ...interface{}) { |
| 50 |
t.Lock() |
| 51 |
defer t.Unlock() |
| 52 |
if t.l != nil { |
| 53 |
t.l.Log(append([]interface{}{time.Now().Format(time.RFC3339Nano), t.prefix}, v...)...) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// Printf formats its arguments according to the format, analogous to fmt.Printf, and |
| 58 |
// records the text in the test log (only printed if the test files or appropriate arguments passed to go test). |
| 59 |
func (t *TestLog) Printf(format string, v ...interface{}) { |
| 60 |
t.Lock() |
| 61 |
defer t.Unlock() |
| 62 |
if t.l != nil { |
| 63 |
t.l.Logf(time.Now().Format(time.RFC3339Nano)+" "+t.prefix+format, v...) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
// Stop prevents future logging |
| 68 |
// func (t *TestLog) Stop() { |
| 69 |
// t.Lock() |
| 70 |
// defer t.Unlock() |
| 71 |
// t.l = nil |
| 72 |
// } |