| 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 state |
| 17 |
|
| 18 |
import "sync" |
| 19 |
|
| 20 |
// logger_test implements a logger than can be passed a testing.T (which will only output logs for failed tests) |
| 21 |
|
| 22 |
// testLogger contains the logging functions provided by testing.T |
| 23 |
type testLogger interface { |
| 24 |
Log(args ...interface{}) |
| 25 |
Logf(format string, args ...interface{}) |
| 26 |
} |
| 27 |
|
| 28 |
// The testLog type is an adapter to allow the use of testing.T as a paho.Logger. |
| 29 |
// With this implementation, log messages will only be output when a test fails (and will be associated with the test). |
| 30 |
type testLog struct { |
| 31 |
sync.Mutex |
| 32 |
l testLogger |
| 33 |
prefix string |
| 34 |
} |
| 35 |
|
| 36 |
// Println prints a line to the log |
| 37 |
// Println its arguments in the test log (only printed if the test files or appropriate arguments passed to go test). |
| 38 |
func (t *testLog) Println(v ...interface{}) { |
| 39 |
t.Lock() |
| 40 |
defer t.Unlock() |
| 41 |
if t.l != nil { |
| 42 |
t.l.Log(append([]interface{}{t.prefix}, v...)...) |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
// Printf formats its arguments according to the format, analogous to fmt.Printf, and |
| 47 |
// records the text in the test log (only printed if the test files or appropriate arguments passed to go test). |
| 48 |
func (t *testLog) Printf(format string, v ...interface{}) { |
| 49 |
t.Lock() |
| 50 |
defer t.Unlock() |
| 51 |
if t.l != nil { |
| 52 |
t.l.Logf(t.prefix+format, v...) |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
// Stop prevents future logging |
| 57 |
func (t *testLog) Stop() { |
| 58 |
t.Lock() |
| 59 |
defer t.Unlock() |
| 60 |
t.l = nil |
| 61 |
} |