* log4j2 examples

* log4j2 examples
This commit is contained in:
lor6 2017-06-01 23:33:52 +03:00 committed by Eugen
parent 3cf4dc5a78
commit d3597a84c7
8 changed files with 288 additions and 0 deletions

4
guest/log4j2-example/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,3 @@
14:00:35.258 INFO Programmatic Logger Message
14:03:51.178 INFO Programmatic Logger Message
14:04:11.753 INFO Programmatic Logger Message

View File

@ -0,0 +1,25 @@
[
{
"timeMillis" : 1496315051753,
"thread" : "main",
"level" : "INFO",
"loggerName" : "RollingFileLogger",
"message" : "Json Message 1",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 1,
"threadPriority" : 5
}
, {
"timeMillis" : 1496315051862,
"thread" : "main",
"level" : "INFO",
"loggerName" : "RollingFileLogger",
"message" : "Json Messag 2",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 1,
"threadPriority" : 5
}
]

View File

@ -0,0 +1,56 @@
<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>log4j2-example</groupId>
<artifactId>log4j2-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources/</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jackson.version>2.8.8.1</jackson.version>
<log4j-core.version>2.8.2</log4j-core.version>
</properties>
</project>

View File

@ -0,0 +1,43 @@
package com.stackify.models;
import java.time.LocalDate;
public class User {
private String name;
private String email;
private LocalDate dateOfBirth;
public User() {
}
public User(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}

View File

@ -0,0 +1,14 @@
package com.stackify.services;
import java.time.LocalDate;
import java.time.Period;
import com.stackify.models.User;
public class MyService {
public int calculateUserAge(User user) {
return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears();
}
}

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<CustomLevels>
<CustomLevel name="NEW_XML_LEVEL" intLevel="350" />
</CustomLevels>
<Filters>
<BurstFilter level="INFO" rate="10" maxBurst="100" />
</Filters>
<Appenders>
<Console name="ColoredConsole" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %highlight{%level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, NEW_LEVEL=black, NEW_XML_LEVEL=black} - %msg%n" />
</Console>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %level - %msg%n" />
</Console>
<RollingFile name="RollingFileAppender" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<JSONLayout complete="true" compact="false" />
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="50 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
<!--
<JDBC name="JDBCAppender" tableName="logs">
<DataSource jndiName="java:/comp/env/jdbc/LoggingDataSource" />
<Column name="date" isEventTimestamp="true" />
<Column name="logger" pattern="%logger" />
<Column name="level" pattern="%level" />
<Column name="message" pattern="%message" />
<Column name="exception" pattern="%ex{full}" />
</JDBC>
<Failover name="FailoverAppender" primary="JDBCAppender">
<Failovers>
<AppenderRef ref="RollingFileAppender" />
<AppenderRef ref="Console" />
</Failovers>
</Failover>
-->
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="ColoredConsole" />
</Root>
<Logger name="ConsoleLogger">
<AppenderRef ref="Console" />
</Logger>
<Logger name="RollingFileLogger">
<AppenderRef ref="RollingFileAppender" />
</Logger>
<!--
<Logger name="JDBCLogger">
<AppenderRef ref="JDBCAppender" />
<RegexFilter regex="*jdbc*" onMatch="ACCEPT" onMismatch="DENY" />
</Logger>
-->
</Loggers>
</Configuration>

View File

@ -0,0 +1,81 @@
package com.stackify.services;
import java.time.LocalDate;
import java.time.Month;
import org.apache.logging.log4j.Level;
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.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.Test;
import com.stackify.models.User;
import com.stackify.services.MyService;
public class MyServiceTest {
private static final Logger logger = LogManager.getLogger(MyServiceTest.class);
@Test
public void testService() {
MyService myService = new MyService();
User user = new User("John", "john@yahoo.com");
user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20));
logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user));
}
@Test
public void testColoredLogger() {
logger.fatal("Fatal level message");
logger.error("Error level message");
logger.warn("Warn level message");
logger.info("Info level message");
logger.debug("Debug level message");
}
@Test
public void testRollingFileAppender() {
Logger rfLogger = LogManager.getLogger("RollingFileLogger");
rfLogger.info("Json Message 1");
rfLogger.info("Json Message 2");
}
@Test
public void testProgrammaticConfig() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();
Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build();
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null);
AppenderRef[] refs = new AppenderRef[] { ref };
LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null);
loggerConfig.addAppender(appender, null, null);
config.addLogger("programmaticLogger", loggerConfig);
ctx.updateLoggers();
Logger pLogger = LogManager.getLogger("programmaticLogger");
pLogger.info("Programmatic Logger Message");
}
@Test
public void testCustomLevel() {
Level myLevel = Level.forName("NEW_LEVEL", 350);
logger.log(myLevel, "Custom Level Message");
logger.log(Level.getLevel("NEW_XML_LEVEL"), "Custom XML Level Message");
}
}