Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dominikjohsdmde committed Jul 25, 2019
0 parents commit 7e4825c
Show file tree
Hide file tree
Showing 21 changed files with 1,447 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/target/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
19 changes: 19 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
language: java
env:
global:
# OSSRH_JIRA_USERNAME
- secure: TPbdHAtQGq73vosBm57yROH+uNIJawNQxPmznne+Djq9NMo+q/iWx2l0Yj9VxJqhVlW4UTzRdqXyzY+kgsECAF1XSICDRvkkzIViBVwoIzz0k9DdwM2Ues5FPNz93cH+Tb1zFM6/+irSa5DzGh9abgVgFC3AW01oJ18CzIWytW+M+lHOfWsuqvlg17ttW0SUX9na2cirk0NPOQTQmkGLxUFwWL56J0tymPSc6+Brg7X3wzGqpvE8wIKm+Wt4deimCfQomWUuyfpi6gnwgPktRgcZE9OWZttPYuKMgfuFOwk5UfkVigorpvWnBQtKCvISJc9wmgiH66xBgH2dzfoFwwk6JTQUhNNqIP5L2AJmjyWEHRY93Pu9L7MKBVSzBjQ5kGhJbF6cDUW2HjSDJkGCQrqFYC4IpWPOhO6HLuFjqqejRuR0rNTp76+KU2L+2ThOF7YQoKazgj1KdQJnQGMKBapYgDq0TOpp3MlFwkJbKhkV7oo9DQmo5hL+V5MvH+u/pEpk9+xCNzxnaOJCBZVIwx7hbhjrK6mnSc2jsq2bnAjDXhgKD01l8JGhzn8LfJ56ay/4EKC5jGp4D20rshm3omscMH/dDyJjRsn7mCtHiVmnz6dC/EByIGcUB5gNjN3ex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A=
jdk: openjdk11
install: mvn install -P !build-extras -DskipTests=true -Dmaven.javadoc.skip=true -B
-V
script: mvn verify -P !build-extras -B
cache:
directories:
- "~/.m2/repository"
after_success: ".travis/deploy_to_maven_central.sh"
Binary file added .travis/codesigning.asc.enc
Binary file not shown.
15 changes: 15 additions & 0 deletions .travis/deploy_to_maven_central.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
if [ "$TRAVIS_BRANCH" = 'master' ] && [ "$TRAVIS_PULL_REQUEST" == 'false' ] || [ ! -z "$TRAVIS_TAG" ]; then
openssl aes-256-cbc -K $encrypted_419f3502ba64_key -iv $encrypted_419f3502ba64_iv -in .travis/codesigning.asc.enc -out .travis/codesigning.asc -d
gpg --fast-import .travis/codesigning.asc

if [ ! -z "$TRAVIS_TAG" ]
then
echo "on a tag -> set pom.xml <version> to $TRAVIS_TAG"
mvn --settings .travis/mvnsettings.xml org.codehaus.mojo:versions-maven-plugin:2.1:set -DnewVersion=$TRAVIS_TAG 1>/dev/null 2>/dev/null
else
echo "not on a tag -> keep snapshot version in pom.xml"
fi

mvn deploy -P sign,build-extras --settings .travis/mvnsettings.xml -DskipTests=true -B -U
fi
28 changes: 28 additions & 0 deletions .travis/mvnsettings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

<servers>
<server>
<id>ossrh</id>
<username>${env.OSSRH_JIRA_USERNAME}</username>
<password>${env.OSSRH_JIRA_PASSWORD}</password>
</server>
</servers>

<profiles>
<profile>
<id>ossrh</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<gpg.executable>gpg</gpg.executable>
<gpg.keyname>${env.GPG_KEY_NAME}</gpg.keyname>
<gpg.passphrase>${env.GPG_PASSPHRASE}</gpg.passphrase>
</properties>

</profile>
</profiles>
</settings>
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2019 dmTECH GmbH, https://www.dmtech.de

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions MAINTAINERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Daniel Flassak <[email protected]> (https://github.com/waschmittel)

224 changes: 224 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
# log-capture

[<img src="https://opensourcelogos.aws.dmtech.cloud/dmTECH_opensource_logo.svg" height="20" width="130">](https://dmtech.de/)
[![Build Status](https://travis-ci.org/dm-drogeriemarkt/log-capture.svg?branch=master)](https://travis-ci.org/dm-drogeriemarkt/log-capture)

Helper for Unit/Integration tests with JUnit 4 to test if something has been logged.

Because this is a library, Checkstyle is used to make sure all public classes/methods have appropriate Javadoc.

## Table of Contents

* [Usage:](#Usage)
* [Examples:](#Examples)
* [Unit Test Example:](#Unit-Test-Example)
* [Integration Test Example:](#Integration-Test-Example)
* [Example with MDC](#Example-with-MDC)
* [Usage with non-JUnit Runner](#Usage-with-non-JUnit-Runner)
* [Cucumber example](#Cucumber-example)
* [Cucumber feature file](#Cucumber-feature-file)
* [Cucumber stepdefs](#Cucumber-stepdefs)
* [Cucumber DTOs](#Cucumber-DTOs)

## Usage:

### Examples:

#### Unit Test Example:

```java
package my.company.application;

...

public class MyUnitTest {

Logger logger = LoggerFactory.getLogger(MyUnitTest.class);

// captures logs from any packages, but only if the log event's call stack
// indicates that it has been caused by the test
@Rule
public LogCapture logCapture = LogCapture.forUnitTest();

@Test
public void twoLogMessagesInOrder() {
log.info("something interesting");
log.error("something terrible");

logCapture
.assertLogged(Level.INFO, "^something interesting$") //second parameter is a regular expression
.thenLogged(Level.ERROR, "terrible");
}
}
```

#### Integration Test Example:

```Java
package my.company.application;

import utility.that.logs.Tool;
import irrelevant.utility.Irrelevant;
...

public class MyIntegrationTest {

Logger logger = LoggerFactory.getLogger(MyIntegrationTest.class);

// captures only logs from my.company and utility.that.logs and sub-packages
@Rule
public LogCapture logCapture = LogCapture.forIntegrationTest("my.company", "utility.that.logs");

@Test
public void twoLogMessagesInOrder() {
Irrelevant.doSomething();
Tool.doSomething();

log.info("something interesting");
log.error("something terrible");

logCapture
.assertLogged(Level.INFO, "^something interesting")
.assertLogged(Level.INFO, "^info from utility.that.logs")
.thenLogged(Level.ERROR, "terrible");
}
}
```

#### Example with MDC

```Java
package my.company.application;

...

import static de.dm.prom.logcapture.ExpectedMdcEntry.withMdc;

...

public class MyUnitTest {
Logger logger = LoggerFactory.getLogger(MyUnitTest.class);

@Rule
public LogCapture logCapture = LogCapture.forUnitTest();

@Test
public void logMessageWithMdcInformation() {
MDC.put("my_mdc_key", "this is the MDC value");
MDC.put("other_mdc_key", "this is the other MDC value");
log.info("this message has some MDC information attached");

logCapture
.assertLogged(Level.INFO, "information attached",
withMdc("my_mdc_key", "^this is the MDC value$"),
withMdc("other_mdc_key", "^this is the other MDC value$")
);
}
}
```

If assertLogged fails because the message is correct, but the MDC value is wrong, the assertion error will contain the actual MDC values of the last captured log event where the log message and level matched.

This can be useful for debugging purposes. For example, this test code:

```java
MDC.put("my_mdc_key", "this is the wrong MDC value");
MDC.put("other_mdc_key", "this is the other MDC value");
log.info("this message has some MDC information attached");

logCapture
.assertLogged(Level.INFO, "information attached",
withMdc("my_mdc_key", "^something expected that never occurs$"),
withMdc("other_mdc_key", "^this is the other MDC value$")
);
```

will output:

```text
java.lang.AssertionError: Expected log message has occurred, but never with the expected MDC value: Level: INFO, Regex: "information attached"
Captured message: "this message has some MDC information attached"
Captured MDC values:
my_mdc_key: "this is the wrong MDC value"
other_mdc_key: "this is the other MDC value"
```


## Usage with non-JUnit Runner

If you intend to use LogCapture outside of a JUnit test, you cannot rely on JUnit's `@Rule` annotation and must call LocCapture's `addAppender()` and `removeAppender()` methods manually.

Be aware that this will still cause JUnit to be a dependency.

### Cucumber example

Here's an Example that shows how to use LogCapture with Cucumber 4:

#### Cucumber feature file

```cucumber
And with MDC logging context
| contextId | contentRegex |
| verkaufsbon_vo | ^MDC_JSON_VALUE:.*2401219817317 |
* the following messages where logged
| level | messageRegex |
| INFO | ^Received bon$ |
```

#### Cucumber stepdefs

You can create these stepdefs in your project to use log-capture in feature files.

```java
public class LoggingStepdefs {
private ExpectedMdcEntry[] expectedMdcEntries;

public LogCapture logCapture = LogCapture.forIntegrationTest("my.company.app");

@Before
public void setupLogCapture() {
logCapture.addAppender();
}

@And("with MDC logging context")
public void withMdcLoggingContext(List<LogContext> logContexts) {
List<ExpectedMdcEntry> expectedMdcEntries = new LinkedList<>();
logContexts.forEach(logContext -> expectedMdcEntries.add(ExpectedMdcEntry.withMdc(logContext.getContextId(), logContext.getContentRegex())));
this.expectedMdcEntries = expectedMdcEntries.toArray(new ExpectedMdcEntry[0]);
}

@And("the following messages where logged")
public void followingMessagedLogged(List<LogEntry> logEntries) {
LogEntry firstEntry = logEntries.get(0);
logEntries.remove(0);
LogCapture.LastCapturedLogEvent lastCapturedLogEvent = logCapture.assertLogged(Level.toLevel(firstEntry.getLevel()), firstEntry.getMessageRegex(), expectedMdcEntries);
for (LogEntry logEntry : logEntries) {
lastCapturedLogEvent = lastCapturedLogEvent.thenLogged(Level.toLevel(logEntry.getLevel()), logEntry.getMessageRegex(), expectedMdcEntries);
}
}
}
```

#### Cucumber DTOs

You need to register these DTOs with Cucumber's [TypeRegistryConfigurer](https://cucumber.io/docs/cucumber/configuration/#type-registry):

```java
import lombok.Data;

@Data
public class LogContext {
private String contextId;
private String contentRegex;
}
```

```java
import lombok.Data;

@Data
public class LogEntry {
private String level;
private String messageRegex;
}
```
Loading

0 comments on commit 7e4825c

Please sign in to comment.