BAEL-41 Intro to Log4J2 code simplification and refactoring
This commit is contained in:
parent
6d9c24ad9e
commit
99c8ee5228
179
log4j2/pom.xml
179
log4j2/pom.xml
@ -1,105 +1,104 @@
|
||||
<?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>
|
||||
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>log4j2</artifactId>
|
||||
<artifactId>log4j2</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- This is the needed core component. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<!-- This is the needed core component. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by JSONLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by JSONLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by XMLLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by XMLLayout. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used by JDBC Appender. -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-dbcp2</artifactId>
|
||||
<version>${commons-dbcp2.version}</version>
|
||||
</dependency>
|
||||
<!-- This is used by JDBC Appender. -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-dbcp2</artifactId>
|
||||
<version>${commons-dbcp2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- This is used for testing only. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<!-- This is used for testing only. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -1,32 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class AsyncFileAppenderUsingJsonLayoutTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-async-file-appender_json-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile()
|
||||
throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is async JSON message #{} at INFO level.", count);
|
||||
}
|
||||
long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count();
|
||||
assertTrue(logEventsCount > 0 && logEventsCount <= count);
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class ConsoleAppenderUsingDefaultLayoutTest {
|
||||
@Test
|
||||
public void givenLoggerWithDefaultConfig_shouldLogToConsole()
|
||||
throws Exception {
|
||||
Logger logger = LogManager.getLogger(getClass());
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.info("This is a simple message at INFO level. " +
|
||||
"It will be hidden.");
|
||||
logger.error("This is a simple message at ERROR level. " +
|
||||
"This is the minimum visible level.", e);
|
||||
}
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class ConsoleAppenderUsingPatternLayoutWithColorsTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-console-appender_pattern-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors()
|
||||
throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
logger.trace("This is a colored message at TRACE level.");
|
||||
logger.debug("This is a colored message at DEBUG level. " +
|
||||
"This is the minimum visible level.");
|
||||
logger.info("This is a colored message at INFO level.");
|
||||
logger.warn("This is a colored message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a colored message at ERROR level.", e);
|
||||
logger.fatal("This is a colored message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
|
||||
Logger logger = contextRule.getLogger("ConnTrace");
|
||||
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
|
||||
Logger logger = contextRule.getLogger("UserAudit");
|
||||
ThreadContext.put("userId", "1000");
|
||||
logger.info("This is a log-visible user login. Maybe from an admin account?");
|
||||
ThreadContext.put("userId", "1001");
|
||||
logger.info("This is a log-invisible user login.");
|
||||
boolean b = true;
|
||||
}
|
||||
}
|
@ -0,0 +1,121 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class CustomLoggingTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
connection.createStatement()
|
||||
.execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)");
|
||||
connection.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithDefaultConfig_shouldLogToConsole() throws Exception {
|
||||
Logger logger = LogManager.getLogger(getClass());
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.info("This is a simple message at INFO level. " + "It will be hidden.");
|
||||
logger.error("This is a simple message at ERROR level. " + "This is the minimum visible level.", e);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
logger.trace("This is a colored message at TRACE level.");
|
||||
logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level.");
|
||||
logger.info("This is a colored message at INFO level.");
|
||||
logger.warn("This is a colored message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a colored message at ERROR level.", e);
|
||||
logger.fatal("This is a colored message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT");
|
||||
ThreadContext.put("userId", "1000");
|
||||
logger.info("This is a log-visible user login. Maybe from an admin account?");
|
||||
ThreadContext.put("userId", "1001");
|
||||
logger.info("This is a log-invisible user login.");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() throws Exception {
|
||||
Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is async JSON message #{} at INFO level.", count);
|
||||
}
|
||||
long logEventsCount = Files.lines(Paths.get("target/logfile.json"))
|
||||
.count();
|
||||
assertTrue(logEventsCount > 0 && logEventsCount <= count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
|
||||
Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER");
|
||||
logger.trace("This is a syslog message at TRACE level.");
|
||||
logger.debug("This is a syslog message at DEBUG level.");
|
||||
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
|
||||
logger.warn("This is a syslog message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a syslog message at ERROR level.", e);
|
||||
logger.fatal("This is a syslog message at FATAL level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
|
||||
Logger logger = LogManager.getLogger("JDBC_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is JDBC message #{} at INFO level.", count);
|
||||
}
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
ResultSet resultSet = connection.createStatement()
|
||||
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
|
||||
int logCount = 0;
|
||||
if (resultSet.next()) {
|
||||
logCount = resultSet.getInt("ROW_COUNT");
|
||||
}
|
||||
assertTrue(logCount == count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
|
||||
Logger logger = LogManager.getLogger("XML_ROLLING_FILE_APPENDER");
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is rolling file XML message #{} at INFO level.", i);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class FailoverSyslogConsoleAppenderTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
logger.trace("This is a syslog message at TRACE level.");
|
||||
logger.debug("This is a syslog message at DEBUG level.");
|
||||
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
|
||||
logger.warn("This is a syslog message at WARN level.");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
logger.error("This is a syslog message at ERROR level.", e);
|
||||
logger.fatal("This is a syslog message at FATAL level.");
|
||||
}
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class JDBCAppenderTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml");
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
connection.createStatement()
|
||||
.execute("CREATE TABLE logs(" +
|
||||
"when TIMESTAMP," +
|
||||
"logger VARCHAR(255)," +
|
||||
"level VARCHAR(255)," +
|
||||
"message VARCHAR(4096)," +
|
||||
"throwable TEXT)");
|
||||
//connection.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is JDBC message #{} at INFO level.", count);
|
||||
}
|
||||
Connection connection = ConnectionFactory.getConnection();
|
||||
ResultSet resultSet = connection.createStatement()
|
||||
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
|
||||
int logCount = 0;
|
||||
if (resultSet.next()) {
|
||||
logCount = resultSet.getInt("ROW_COUNT");
|
||||
}
|
||||
assertTrue(logCount == count);
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.junit.LoggerContextRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class RollingFileAppenderUsingXMLLayoutTest {
|
||||
@Rule
|
||||
public LoggerContextRule contextRule =
|
||||
new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml");
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
|
||||
Logger logger = contextRule.getLogger(getClass().getSimpleName());
|
||||
final int count = 88;
|
||||
for (int i = 0; i < count; i++) {
|
||||
logger.info("This is rolling file XML message #{} at INFO level.", i);
|
||||
}
|
||||
String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream()
|
||||
.collect(Collectors.joining(System.lineSeparator()))
|
||||
.split("\\n\\n+");
|
||||
assertTrue(logEvents.length == 39);
|
||||
}
|
||||
}
|
@ -2,7 +2,6 @@ package com.baeldung.logging.log4j2.tests.jdbc;
|
||||
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
import org.h2.Driver;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
|
@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<File name="JSONLogfileAppender" fileName="target/logfile.json">
|
||||
<JSONLayout compact="true" eventEol="true"/>
|
||||
<BurstFilter level="INFO" rate="2" maxBurst="10"/>
|
||||
</File>
|
||||
<Async name="AsyncAppender" bufferSize="80">
|
||||
<AppenderRef ref="JSONLogfileAppender"/>
|
||||
</Async>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="INFO">
|
||||
<AppenderRef ref="AsyncAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -1,27 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||
<Appenders>
|
||||
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
|
||||
<Console name="ConsoleRedAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%style{%message}{red}%n"/>
|
||||
<MarkerFilter marker="CONN_TRACE"/>
|
||||
</Console>
|
||||
<Console name="ConsoleGreenAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%style{userId=%X{userId}:}{white} %style{%message}{green}%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Logger name="ConnTrace" level="TRACE" additivity="false">
|
||||
<AppenderRef ref="ConsoleRedAppender"/>
|
||||
</Logger>
|
||||
<Logger name="UserAudit" level="INFO" additivity="false">
|
||||
<AppenderRef ref="ConsoleGreenAppender"/>
|
||||
<ThreadContextMapFilter>
|
||||
<KeyValuePair key="userId" value="1000"/>
|
||||
</ThreadContextMapFilter>
|
||||
</Logger>
|
||||
<Root level="DEBUG">
|
||||
<AppenderRef ref="ConsoleAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -1,20 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||
<Appenders>
|
||||
|
||||
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
|
||||
|
||||
<Syslog name="Syslog" host="localhost" port="514" protocol="TCP" ignoreExceptions="false"/>
|
||||
|
||||
<Failover name="FailoverAppender" primary="Syslog">
|
||||
<Failovers>
|
||||
<AppenderRef ref="ConsoleAppender"/>
|
||||
</Failovers>
|
||||
</Failover>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="TRACE">
|
||||
<AppenderRef ref="FailoverAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -1,4 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Console name="ConsoleAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow} [%style{%thread}{white}] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, TRACE=blue} %style{%logger{36}}{cyan}:%n[+] %message%n%throwable"/>
|
||||
<PatternLayout
|
||||
pattern="%style{%date{DEFAULT}}{yellow} [%style{%thread}{white}] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, TRACE=blue} %style{%logger{36}}{cyan}:%n[+] %message%n%throwable" />
|
||||
</Console>
|
||||
|
@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<JDBC name="JDBCAppender" tableName="logs">
|
||||
<ConnectionFactory class="com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory"
|
||||
method="getConnection"/>
|
||||
<Column name="when" isEventTimestamp="true"/>
|
||||
<Column name="logger" pattern="%logger"/>
|
||||
<Column name="level" pattern="%level"/>
|
||||
<Column name="message" pattern="%message"/>
|
||||
<Column name="throwable" pattern="%ex{full}"/>
|
||||
</JDBC>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="trace">
|
||||
<AppenderRef ref="JDBCAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<RollingFile name="XMLLogfileAppender"
|
||||
fileName="target/logfile.xml"
|
||||
filePattern="target/logfile-%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<XMLLayout/>
|
||||
<Policies>
|
||||
<SizeBasedTriggeringPolicy size="17 kB"/>
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="TRACE">
|
||||
<AppenderRef ref="XMLLogfileAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
@ -1,13 +1,69 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Configuration xmlns:xi="http://www.w3.org/2001/XInclude" status="WARN">
|
||||
<Appenders>
|
||||
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml" />
|
||||
<Console name="ConsoleAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable"/>
|
||||
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable" />
|
||||
</Console>
|
||||
<Console name="ConsoleRedAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%style{%message}{red}%n" />
|
||||
<MarkerFilter marker="CONN_TRACE" />
|
||||
</Console>
|
||||
<Console name="ConsoleGreenAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%style{userId=%X{userId}:}{white} %style{%message}{green}%n" />
|
||||
</Console>
|
||||
<File name="JSONLogfileAppender" fileName="target/logfile.json">
|
||||
<JSONLayout compact="true" eventEol="true" />
|
||||
<BurstFilter level="INFO" rate="2" maxBurst="10" />
|
||||
</File>
|
||||
<Async name="AsyncAppender" bufferSize="80">
|
||||
<AppenderRef ref="JSONLogfileAppender" />
|
||||
</Async>
|
||||
<Syslog name="Syslog" format="RFC5424" host="localhost" port="514" protocol="TCP" facility="local3" connectTimeoutMillis="10000" reconnectionDelayMillis="5000" />
|
||||
<Failover name="FailoverAppender" primary="Syslog">
|
||||
<Failovers>
|
||||
<AppenderRef ref="ConsoleAppender" />
|
||||
</Failovers>
|
||||
</Failover>
|
||||
<JDBC name="JDBCAppender" tableName="logs">
|
||||
<ConnectionFactory class="com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory" method="getConnection" />
|
||||
<Column name="when" isEventTimestamp="true" />
|
||||
<Column name="logger" pattern="%logger" />
|
||||
<Column name="level" pattern="%level" />
|
||||
<Column name="message" pattern="%message" />
|
||||
<Column name="throwable" pattern="%ex{full}" />
|
||||
</JDBC>
|
||||
<RollingFile name="XMLRollingfileAppender" fileName="target/logfile.xml" filePattern="target/logfile-%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<XMLLayout />
|
||||
<Policies>
|
||||
<SizeBasedTriggeringPolicy size="17 kB" />
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="ERROR">
|
||||
<AppenderRef ref="ConsoleAppender"/>
|
||||
<Logger name="CONSOLE_PATTERN_APPENDER_MARKER" level="TRACE" additivity="false">
|
||||
<AppenderRef ref="ConsoleRedAppender" />
|
||||
</Logger>
|
||||
<Logger name="CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT" level="INFO" additivity="false">
|
||||
<AppenderRef ref="ConsoleGreenAppender" />
|
||||
<ThreadContextMapFilter>
|
||||
<KeyValuePair key="userId" value="1000" />
|
||||
</ThreadContextMapFilter>
|
||||
</Logger>
|
||||
<Logger name="ASYNC_JSON_FILE_APPENDER" level="INFO" additivity="false">
|
||||
<AppenderRef ref="AsyncAppender" />
|
||||
</Logger>
|
||||
<Logger name="FAIL_OVER_SYSLOG_APPENDER" level="INFO" additivity="false">
|
||||
<AppenderRef ref="FailoverAppender" />
|
||||
</Logger>
|
||||
<Logger name="JDBC_APPENDER" level="INFO" additivity="false">
|
||||
<AppenderRef ref="JDBCAppender" />
|
||||
</Logger>
|
||||
<Logger name="XML_ROLLING_FILE_APPENDER" level="INFO" additivity="false">
|
||||
<AppenderRef ref="XMLRollingfileAppender" />
|
||||
</Logger>
|
||||
<Root level="DEBUG">
|
||||
<AppenderRef ref="ConsoleAppender" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
</Configuration>
|
Loading…
x
Reference in New Issue
Block a user