Skip to content

Commit

Permalink
[BAEL-2111] guest | Why SLF4J? 10 Reasons to use it (eugenp#5536)
Browse files Browse the repository at this point in the history
*  Added new submodule for SLF4J guest post, containg modules for logback, log4j and log4j2

* * added tests for logging endpoints
* removed application tests, no use now that we have other tests
  • Loading branch information
rozagerardo authored and maibin committed Oct 28, 2018
1 parent c10101a commit be22bd2
Show file tree
Hide file tree
Showing 31 changed files with 1,044 additions and 0 deletions.
64 changes: 64 additions & 0 deletions guest/slf4j/guide/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.stackify.slf4j.guide</groupId>
<artifactId>slf4j-parent-module</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>

<modules>
<module>slf4j-logback</module>
<module>slf4j-log4j2</module>
<module>slf4j-log4j</module>
</modules>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<powermock.version>2.0.0-beta.5</powermock.version>
</properties>
</project>
25 changes: 25 additions & 0 deletions guest/slf4j/guide/slf4j-log4j/.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/
41 changes: 41 additions & 0 deletions guest/slf4j/guide/slf4j-log4j/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>slf4j-log4j</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<parent>
<groupId>com.stackify.slf4j.guide</groupId>
<artifactId>slf4j-parent-module</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<slf4j.log4j.version>1.7.25</slf4j.log4j.version>
</properties>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.stackify.slf4j.guide;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.stackify.slf4j.guide.controllers;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SimpleController {

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

@GetMapping("/slf4j-guide-request")
public String processList(List<String> list) {
logger.info("Client requested process the following list: {}", list);
try {
logger.debug("Starting process");
// ...processing list here...
Thread.sleep(500);
} catch (RuntimeException | InterruptedException e) {
logger.error("There was an issue processing the list.", e);
} finally {
logger.info("Finished processing");
}
return "done";
}

@GetMapping("/slf4j-guide-mdc-request")
public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException {
MDC.put("clientId", clientId);
logger.info("Client {} has made a request", clientId);
logger.info("Starting request");
Thread.sleep(500);
logger.info("Finished request");
MDC.clear();
return "finished";
}
}
Empty file.
17 changes: 17 additions & 0 deletions guest/slf4j/guide/slf4j-log4j/src/main/resources/log4j.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p %d{ISO8601} [%X{clientId}@%t][%x] %c - %m%n"/>
</layout>
</appender>

<root>
<priority value ="info" />
<appender-ref ref="console" />
</root>

</log4j:configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.stackify.slf4j.guide.controllers;

import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;

import java.util.Collections;

import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.assertj.core.api.Condition;
import org.assertj.core.api.SoftAssertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.MDC;

import com.stackify.slf4j.guide.utils.ListAppender;

@RunWith(PowerMockRunner.class)
@PrepareForTest(MDC.class)
public class SimpleControllerIntegrationTest {

private SimpleController controller = new SimpleController();

@Before
public void clearLogList() {
ListAppender.clearEventList();
}

@Test
public void whenSimpleRequestMade_thenAllRegularMessagesLogged() {
String output = controller.processList(Collections.emptyList());

SoftAssertions errorCollector = new SoftAssertions();
errorCollector.assertThat(ListAppender.getEvents())
.haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO))
.haveAtLeastOne(eventContains("Starting process", Level.DEBUG))
.haveAtLeastOne(eventContains("Finished processing", Level.INFO))
.haveExactly(0, eventOfLevel(Level.ERROR));
errorCollector.assertThat(output)
.isEqualTo("done");
errorCollector.assertAll();
}

@Test
public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception {
// We avoid cleaning the context so tht we can check it afterwards
spy(MDC.class);
doNothing().when(MDC.class);
MDC.clear();
String clientId = "id-1234";

String output = controller.clientMDCRequest(clientId);

SoftAssertions errorCollector = new SoftAssertions();
errorCollector.assertThat(ListAppender.getEvents())
.allMatch(entry -> {
return clientId.equals(entry.getMDC("clientId"));
})
.haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO))
.haveAtLeastOne(eventContains("Starting request", Level.INFO))
.haveAtLeastOne(eventContains("Finished request", Level.INFO));
errorCollector.assertThat(output)
.isEqualTo("finished");
errorCollector.assertAll();

}

private Condition<LoggingEvent> eventOfLevel(Level level) {
return eventContains(null, level);
}

private Condition<LoggingEvent> eventContains(String substring, Level level) {

return new Condition<LoggingEvent>(entry -> (substring == null || (entry.getRenderedMessage() != null && entry.getRenderedMessage()
.contains(substring))) && (level == null || level.equals(entry.getLevel())), String.format("entry with message '%s', level %s", substring, level));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.stackify.slf4j.guide.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class ListAppender extends AppenderSkeleton {
public static List<LoggingEvent> events = new ArrayList<LoggingEvent>();

@Override
public void close() {
}

@Override
public boolean requiresLayout() {
return false;
}

@Override
protected void append(LoggingEvent event) {
events.add(event);
}

public static List<LoggingEvent> getEvents() {
return events;
}

public static void clearEventList() {
events.clear();
}
}
16 changes: 16 additions & 0 deletions guest/slf4j/guide/slf4j-log4j/src/test/resources/log4j.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
</appender>
<appender name="list" class="com.stackify.slf4j.guide.utils.ListAppender">
</appender>

<root>
<priority value ="trace" />
<appender-ref ref="list" />
</root>

</log4j:configuration>
25 changes: 25 additions & 0 deletions guest/slf4j/guide/slf4j-log4j2/.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/
Loading

0 comments on commit be22bd2

Please sign in to comment.