Merge pull request #818 from christian-raedel/craedel-log4j2

BAEL-41: craedel-log4j2
This commit is contained in:
Grzegorz Piwowarek 2016-11-14 21:55:48 +01:00 committed by GitHub
commit ea18d3a4b3
15 changed files with 438 additions and 0 deletions

79
log4j2/pom.xml Normal file
View File

@ -0,0 +1,79 @@
<?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>log4j2</artifactId>
<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>2.7</version>
</dependency>
<!-- This is used by JSONLayout. -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.4</version>
</dependency>
<!-- This is used by XMLLayout. -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.4</version>
</dependency>
<!-- This is used by JDBC Appender. -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<!-- This is used for testing only. -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,32 @@
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);
}
}

View File

@ -0,0 +1,21 @@
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);
}
}

View File

@ -0,0 +1,51 @@
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;
}
}

View File

@ -0,0 +1,27 @@
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.");
}
}

View File

@ -0,0 +1,51 @@
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);
}
}

View File

@ -0,0 +1,34 @@
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);
}
}

View File

@ -0,0 +1,25 @@
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;
public class ConnectionFactory {
private interface Singleton {
ConnectionFactory INSTANCE = new ConnectionFactory();
}
private BasicDataSource dataSource;
private ConnectionFactory() {
dataSource = new BasicDataSource();
dataSource.setDriver(new Driver());
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
}
public static Connection getConnection() throws SQLException {
return Singleton.INSTANCE.dataSource.getConnection();
}
}

View File

@ -0,0 +1,17 @@
<?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>

View File

@ -0,0 +1,27 @@
<?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>

View File

@ -0,0 +1,20 @@
<?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>

View File

@ -0,0 +1,4 @@
<?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"/>
</Console>

View File

@ -0,0 +1,19 @@
<?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>

View File

@ -0,0 +1,18 @@
<?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>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n%throwable"/>
</Console>
</Appenders>
<Loggers>
<Root level="ERROR">
<AppenderRef ref="ConsoleAppender"/>
</Root>
</Loggers>
</Configuration>