[JAVA-11417] Fix log4j2 JSON integration test

This commit is contained in:
Haroon Khan 2022-04-26 20:13:08 +01:00
parent d49fe65f1d
commit 3cc6b034b8
1 changed files with 37 additions and 26 deletions

View File

@ -1,47 +1,58 @@
package com.baeldung.logging.log4j2.tests;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.appender.WriterAppender;
import org.apache.logging.log4j.core.layout.JsonLayout;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.CharArrayWriter;
import java.io.Writer;
import static org.junit.Assert.assertTrue;
public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest {
private static Logger logger;
private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
private PrintStream ps = new PrintStream(consoleOutput);
private Appender appender;
private Logger logger;
private final Writer writer = new CharArrayWriter();
@Before
public void setUp() {
// Redirect console output to our stream
System.setOut(ps);
logger = LogManager.getLogger("CONSOLE_JSON_APPENDER");
appender = WriterAppender.newBuilder()
.setTarget(writer)
.setLayout(JsonLayout.newBuilder().build())
.setName("json_layout_for_testing")
.build();
appender.start();
((org.apache.logging.log4j.core.Logger) logger).addAppender(appender);
}
@Test
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() {
public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() throws Exception {
logger.debug("Debug message");
String currentLog = consoleOutput.toString();
assertTrue(currentLog.isEmpty());
assertTrue(isValidJSON(currentLog));
writer.flush();
assertTrue(isValidJSON(writer.toString()));
}
public static boolean isValidJSON(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
@After
public void cleanup() {
((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender);
}
}
private static boolean isValidJSON(String jsonInString) throws Exception {
JsonNode jsonNode = new ObjectMapper().readTree(jsonInString);
return jsonNode.get("message").asText().equals("Debug message");
}
}