Skip to content

Commit ea18d3a

Browse files
authored
Merge pull request eugenp#818 from christian-raedel/craedel-log4j2
BAEL-41: craedel-log4j2
2 parents dbe099f + 6d1fbd5 commit ea18d3a

15 files changed

Lines changed: 438 additions & 0 deletions

‎log4j2/pom.xml‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<artifactId>log4j2</artifactId>
8+
9+
<parent>
10+
<groupId>com.baeldung</groupId>
11+
<artifactId>parent-modules</artifactId>
12+
<version>1.0.0-SNAPSHOT</version>
13+
<relativePath>..</relativePath>
14+
</parent>
15+
16+
<dependencies>
17+
<!-- This is the needed core component. -->
18+
<dependency>
19+
<groupId>org.apache.logging.log4j</groupId>
20+
<artifactId>log4j-core</artifactId>
21+
<version>2.7</version>
22+
</dependency>
23+
24+
<!-- This is used by JSONLayout. -->
25+
<dependency>
26+
<groupId>com.fasterxml.jackson.core</groupId>
27+
<artifactId>jackson-databind</artifactId>
28+
<version>2.8.4</version>
29+
</dependency>
30+
31+
<!-- This is used by XMLLayout. -->
32+
<dependency>
33+
<groupId>com.fasterxml.jackson.dataformat</groupId>
34+
<artifactId>jackson-dataformat-xml</artifactId>
35+
<version>2.8.4</version>
36+
</dependency>
37+
38+
<!-- This is used by JDBC Appender. -->
39+
<dependency>
40+
<groupId>com.h2database</groupId>
41+
<artifactId>h2</artifactId>
42+
<version>1.4.192</version>
43+
</dependency>
44+
<dependency>
45+
<groupId>org.apache.commons</groupId>
46+
<artifactId>commons-dbcp2</artifactId>
47+
<version>2.1.1</version>
48+
</dependency>
49+
50+
<!-- This is used for testing only. -->
51+
<dependency>
52+
<groupId>org.apache.logging.log4j</groupId>
53+
<artifactId>log4j-core</artifactId>
54+
<version>2.7</version>
55+
<type>test-jar</type>
56+
<scope>test</scope>
57+
</dependency>
58+
<dependency>
59+
<groupId>junit</groupId>
60+
<artifactId>junit</artifactId>
61+
<version>4.12</version>
62+
<scope>test</scope>
63+
</dependency>
64+
</dependencies>
65+
66+
<build>
67+
<plugins>
68+
<plugin>
69+
<groupId>org.apache.maven.plugins</groupId>
70+
<artifactId>maven-compiler-plugin</artifactId>
71+
<version>3.5.1</version>
72+
<configuration>
73+
<source>1.8</source>
74+
<target>1.8</target>
75+
</configuration>
76+
</plugin>
77+
</plugins>
78+
</build>
79+
</project>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import org.apache.logging.log4j.Logger;
4+
import org.apache.logging.log4j.junit.LoggerContextRule;
5+
import org.junit.Rule;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.junit.runners.JUnit4;
9+
10+
import java.nio.file.Files;
11+
import java.nio.file.Paths;
12+
13+
import static org.junit.Assert.assertTrue;
14+
15+
@RunWith(JUnit4.class)
16+
public class AsyncFileAppenderUsingJsonLayoutTest {
17+
@Rule
18+
public LoggerContextRule contextRule =
19+
new LoggerContextRule("log4j2-async-file-appender_json-layout.xml");
20+
21+
@Test
22+
public void givenLoggerWithAsyncConfig_shouldLogToJsonFile()
23+
throws Exception {
24+
Logger logger = contextRule.getLogger(getClass().getSimpleName());
25+
final int count = 88;
26+
for (int i = 0; i < count; i++) {
27+
logger.info("This is async JSON message #{} at INFO level.", count);
28+
}
29+
long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count();
30+
assertTrue(logEventsCount > 0 && logEventsCount <= count);
31+
}
32+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import org.apache.logging.log4j.LogManager;
4+
import org.apache.logging.log4j.Logger;
5+
import org.junit.Test;
6+
import org.junit.runner.RunWith;
7+
import org.junit.runners.JUnit4;
8+
9+
@RunWith(JUnit4.class)
10+
public class ConsoleAppenderUsingDefaultLayoutTest {
11+
@Test
12+
public void givenLoggerWithDefaultConfig_shouldLogToConsole()
13+
throws Exception {
14+
Logger logger = LogManager.getLogger(getClass());
15+
Exception e = new RuntimeException("This is only a test!");
16+
logger.info("This is a simple message at INFO level. " +
17+
"It will be hidden.");
18+
logger.error("This is a simple message at ERROR level. " +
19+
"This is the minimum visible level.", e);
20+
}
21+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import org.apache.logging.log4j.Logger;
4+
import org.apache.logging.log4j.Marker;
5+
import org.apache.logging.log4j.MarkerManager;
6+
import org.apache.logging.log4j.ThreadContext;
7+
import org.apache.logging.log4j.junit.LoggerContextRule;
8+
import org.junit.Rule;
9+
import org.junit.Test;
10+
import org.junit.runner.RunWith;
11+
import org.junit.runners.JUnit4;
12+
13+
@RunWith(JUnit4.class)
14+
public class ConsoleAppenderUsingPatternLayoutWithColorsTest {
15+
@Rule
16+
public LoggerContextRule contextRule =
17+
new LoggerContextRule("log4j2-console-appender_pattern-layout.xml");
18+
19+
@Test
20+
public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors()
21+
throws Exception {
22+
Logger logger = contextRule.getLogger(getClass().getSimpleName());
23+
logger.trace("This is a colored message at TRACE level.");
24+
logger.debug("This is a colored message at DEBUG level. " +
25+
"This is the minimum visible level.");
26+
logger.info("This is a colored message at INFO level.");
27+
logger.warn("This is a colored message at WARN level.");
28+
Exception e = new RuntimeException("This is only a test!");
29+
logger.error("This is a colored message at ERROR level.", e);
30+
logger.fatal("This is a colored message at FATAL level.");
31+
}
32+
33+
@Test
34+
public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception {
35+
Logger logger = contextRule.getLogger("ConnTrace");
36+
Marker appError = MarkerManager.getMarker("APP_ERROR");
37+
logger.error(appError, "This marker message at ERROR level should be hidden.");
38+
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
39+
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
40+
}
41+
42+
@Test
43+
public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception {
44+
Logger logger = contextRule.getLogger("UserAudit");
45+
ThreadContext.put("userId", "1000");
46+
logger.info("This is a log-visible user login. Maybe from an admin account?");
47+
ThreadContext.put("userId", "1001");
48+
logger.info("This is a log-invisible user login.");
49+
boolean b = true;
50+
}
51+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import org.apache.logging.log4j.Logger;
4+
import org.apache.logging.log4j.junit.LoggerContextRule;
5+
import org.junit.Rule;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.junit.runners.JUnit4;
9+
10+
@RunWith(JUnit4.class)
11+
public class FailoverSyslogConsoleAppenderTest {
12+
@Rule
13+
public LoggerContextRule contextRule =
14+
new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml");
15+
16+
@Test
17+
public void givenLoggerWithFailoverConfig_shouldLog() throws Exception {
18+
Logger logger = contextRule.getLogger(getClass().getSimpleName());
19+
logger.trace("This is a syslog message at TRACE level.");
20+
logger.debug("This is a syslog message at DEBUG level.");
21+
logger.info("This is a syslog message at INFO level. This is the minimum visible level.");
22+
logger.warn("This is a syslog message at WARN level.");
23+
Exception e = new RuntimeException("This is only a test!");
24+
logger.error("This is a syslog message at ERROR level.", e);
25+
logger.fatal("This is a syslog message at FATAL level.");
26+
}
27+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory;
4+
import org.apache.logging.log4j.Logger;
5+
import org.apache.logging.log4j.junit.LoggerContextRule;
6+
import org.junit.BeforeClass;
7+
import org.junit.Rule;
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.junit.runners.JUnit4;
11+
12+
import java.sql.Connection;
13+
import java.sql.ResultSet;
14+
15+
import static org.junit.Assert.assertTrue;
16+
17+
@RunWith(JUnit4.class)
18+
public class JDBCAppenderTest {
19+
@Rule
20+
public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml");
21+
22+
@BeforeClass
23+
public static void setup() throws Exception {
24+
Connection connection = ConnectionFactory.getConnection();
25+
connection.createStatement()
26+
.execute("CREATE TABLE logs(" +
27+
"when TIMESTAMP," +
28+
"logger VARCHAR(255)," +
29+
"level VARCHAR(255)," +
30+
"message VARCHAR(4096)," +
31+
"throwable TEXT)");
32+
//connection.commit();
33+
}
34+
35+
@Test
36+
public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception {
37+
Logger logger = contextRule.getLogger(getClass().getSimpleName());
38+
final int count = 88;
39+
for (int i = 0; i < count; i++) {
40+
logger.info("This is JDBC message #{} at INFO level.", count);
41+
}
42+
Connection connection = ConnectionFactory.getConnection();
43+
ResultSet resultSet = connection.createStatement()
44+
.executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs");
45+
int logCount = 0;
46+
if (resultSet.next()) {
47+
logCount = resultSet.getInt("ROW_COUNT");
48+
}
49+
assertTrue(logCount == count);
50+
}
51+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.logging.log4j2.tests;
2+
3+
import org.apache.logging.log4j.Logger;
4+
import org.apache.logging.log4j.junit.LoggerContextRule;
5+
import org.junit.Rule;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.junit.runners.JUnit4;
9+
10+
import java.nio.file.Files;
11+
import java.nio.file.Paths;
12+
import java.util.stream.Collectors;
13+
14+
import static org.junit.Assert.assertTrue;
15+
16+
@RunWith(JUnit4.class)
17+
public class RollingFileAppenderUsingXMLLayoutTest {
18+
@Rule
19+
public LoggerContextRule contextRule =
20+
new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml");
21+
22+
@Test
23+
public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception {
24+
Logger logger = contextRule.getLogger(getClass().getSimpleName());
25+
final int count = 88;
26+
for (int i = 0; i < count; i++) {
27+
logger.info("This is rolling file XML message #{} at INFO level.", i);
28+
}
29+
String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream()
30+
.collect(Collectors.joining(System.lineSeparator()))
31+
.split("\\n\\n+");
32+
assertTrue(logEvents.length == 39);
33+
}
34+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.logging.log4j2.tests.jdbc;
2+
3+
import org.apache.commons.dbcp2.BasicDataSource;
4+
import org.h2.Driver;
5+
6+
import java.sql.Connection;
7+
import java.sql.SQLException;
8+
9+
public class ConnectionFactory {
10+
private interface Singleton {
11+
ConnectionFactory INSTANCE = new ConnectionFactory();
12+
}
13+
14+
private BasicDataSource dataSource;
15+
16+
private ConnectionFactory() {
17+
dataSource = new BasicDataSource();
18+
dataSource.setDriver(new Driver());
19+
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
20+
}
21+
22+
public static Connection getConnection() throws SQLException {
23+
return Singleton.INSTANCE.dataSource.getConnection();
24+
}
25+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Configuration status="WARN">
3+
<Appenders>
4+
<File name="JSONLogfileAppender" fileName="target/logfile.json">
5+
<JSONLayout compact="true" eventEol="true"/>
6+
<BurstFilter level="INFO" rate="2" maxBurst="10"/>
7+
</File>
8+
<Async name="AsyncAppender" bufferSize="80">
9+
<AppenderRef ref="JSONLogfileAppender"/>
10+
</Async>
11+
</Appenders>
12+
<Loggers>
13+
<Root level="INFO">
14+
<AppenderRef ref="AsyncAppender"/>
15+
</Root>
16+
</Loggers>
17+
</Configuration>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Configuration status="WARN" xmlns:xi="http://www.w3.org/2001/XInclude">
3+
<Appenders>
4+
<xi:include href="log4j2-includes/console-appender_pattern-layout_colored.xml"/>
5+
<Console name="ConsoleRedAppender" target="SYSTEM_OUT">
6+
<PatternLayout pattern="%style{%message}{red}%n"/>
7+
<MarkerFilter marker="CONN_TRACE"/>
8+
</Console>
9+
<Console name="ConsoleGreenAppender" target="SYSTEM_OUT">
10+
<PatternLayout pattern="%style{userId=%X{userId}:}{white} %style{%message}{green}%n"/>
11+
</Console>
12+
</Appenders>
13+
<Loggers>
14+
<Logger name="ConnTrace" level="TRACE" additivity="false">
15+
<AppenderRef ref="ConsoleRedAppender"/>
16+
</Logger>
17+
<Logger name="UserAudit" level="INFO" additivity="false">
18+
<AppenderRef ref="ConsoleGreenAppender"/>
19+
<ThreadContextMapFilter>
20+
<KeyValuePair key="userId" value="1000"/>
21+
</ThreadContextMapFilter>
22+
</Logger>
23+
<Root level="DEBUG">
24+
<AppenderRef ref="ConsoleAppender"/>
25+
</Root>
26+
</Loggers>
27+
</Configuration>

0 commit comments

Comments
 (0)