https://github.com/nalbion/test-appender
Allows logging output of Java applications to be tested
https://github.com/nalbion/test-appender
logger logging testing
Last synced: 8 months ago
JSON representation
Allows logging output of Java applications to be tested
- Host: GitHub
- URL: https://github.com/nalbion/test-appender
- Owner: nalbion
- License: mit
- Created: 2022-09-07T11:51:54.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2023-09-06T04:59:17.000Z (almost 3 years ago)
- Last Synced: 2025-04-03T07:44:54.031Z (about 1 year ago)
- Topics: logger, logging, testing
- Language: Java
- Homepage:
- Size: 28.3 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Test Appender

[](https://lift.sonatype.com/results/github.com/nalbion/test-appender)
By taking TDD one step further, and specifying what the logging output should look like before writing the code
we can expect that the logs will give maintainers clear and useful logs.
Based on Jaroslaw Michalik's article [Don't mock static: test SLF4J Logger with appenders](https://kotlintesting.com/mock-slf4j/).
For JavaScript applications, refer to [log-dd](https://github.com/nalbion/log-dd).
`TestAppender` assumes that the application uses `ch.qos.logback.classic.Logger`, which is the default provided by Spring Boot.
## Installation
This library is available from [Maven Central](https://s01.oss.sonatype.org/) or
[Git Hub Packages](https://github.com/nalbion/test-appender/packages)
### Gradle
```groovy
dependencies {
...
testImplementation 'io.github.nalbion:test-appender:1.0.3'
}
```
### Maven
```xml
...
io.github.nalbion
test-appender
1.0.3
test
```
## Usage
```java
...
import io.github.nalbion.TestAppender;
import org.junit.jupiter.api.Test;
class MyTest {
private final TestAppender testAppender = new TestAppender(true);
@BeforeEach
void setup() {
testAppender.start();
}
@Test
void myTest() {
// When
new MyApplication().doSomething();
// Then
// Check all logs match a multi-line string
testAppender.assertLogs("""
Hello World!
My application calls log.info() twice.""");
// Check that only some lines are logged at WARN
testAppender.assertLogs(Level.WARN, "My application calls log.info() twice.");
// Check that at least one of the lines matches a Predicate
testAppender.assertAnyLogs(
TestAppender.atLogLevel(Level.INFO)
.and(e -> e.getFormattedMessage().matches("Hello .*!"))
);
testAppender.assertNoLogs(e -> e.getFormattedMessage().matches("Password: .*!"));
}
@Test
void dynamicValues() {
// When
logger.info("The time is {}", new SimpleDateFormat("HH:mm").format(new Date()));
// Then
// Handle dynamic values - date/time, random values
testAppender.assertLogs(line -> line.replaceFirst("\\b\\d{1,2}:\\d{2}\\b", "hh:mm"),
"The time is hh:mm");
}
}
```