logback example app (#2354)

This commit is contained in:
lor6 2017-08-22 14:22:49 +03:00 committed by Grzegorz Piwowarek
parent 8a34433095
commit dc867672e9
7 changed files with 349 additions and 0 deletions

View File

@ -0,0 +1,41 @@
<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>com.stackify</groupId>
<artifactId>logback-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.logging;
import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
public class IgnoreLoggerFilter extends TurboFilter {
private String loggerName;
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if (loggerName == null) {
return FilterReply.NEUTRAL;
} else if (loggerName.equals(logger.getName())) {
return FilterReply.DENY;
} else
return FilterReply.NEUTRAL;
}
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
}

View File

@ -0,0 +1,43 @@
package com.stackify.models;
public class Employee {
private String email;
private String name;
private double salary;
public Employee() {
}
public Employee(String email, String name, double salary) {
this.email = email;
this.name = name;
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,11 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee user) {
return 0.1 * user.getSalary();
}
}

View File

@ -0,0 +1 @@
env=dev

View File

@ -0,0 +1,151 @@
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.out</target>
</appender>
<property name="fileName" value="file.log" />
<property scope="context" resource="application.properties" />
<!-- configure appenders -->
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>3MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>userRole</key>
<defaultValue>ANONYMOUS</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
<file>${userRole}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [%thread] %level %mdc %logger{50} - %msg%n</pattern>
</layout>
</appender>
</sift>
</appender>
<!-- configure layouts -->
<appender name="colorAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="htmlAppender" class="ch.qos.logback.core.FileAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%thread%level%logger%msg</pattern>
</layout>
</encoder>
<file>log.html</file>
</appender>
<!-- configure filters -->
<appender name="STDOUT_LEVEL_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.err</target>
</appender>
<appender name="STDOUT_THRESHOLD_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT_EVALUATOR_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>return (level > DEBUG &amp;&amp; message.toLowerCase().contains("employee"));</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- configure turbo filters -->
<turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter">
<AllowedRepetitions>2</AllowedRepetitions>
</turboFilter>
<turboFilter class="com.stackify.logging.IgnoreLoggerFilter">
<LoggerName>ignoredColorLogger</LoggerName>
</turboFilter>
<!-- configure loggers -->
<logger level="info" name="rollingFileLogger" additivity="false">
<appender-ref ref="rollingFileAppender" />
</logger>
<logger level="info" name="htmlLogger" additivity="false">
<appender-ref ref="htmlAppender" />
</logger>
<logger level="info" name="roleSiftingLogger" additivity="false">
<appender-ref ref="roleSiftingAppender" />
</logger>
<logger level="info" name="colorLogger" additivity="false">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="ignoredColorLogger">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="levelFilterLogger" additivity="false">
<appender-ref ref="STDOUT_LEVEL_FILTER_APPENDER" />
</logger>
<logger level="info" name="thresholdFilterLogger" additivity="false">
<appender-ref ref="STDOUT_THRESHOLD_FILTER_APPENDER" />
</logger>
<logger level="info" name="evaluatorFilterLogger" additivity="false">
<appender-ref ref="STDOUT_EVALUATOR_FILTER_APPENDER" />
</logger>
<!-- configure root logger -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- configure root logger conditionally -->
<property scope="context" resource="application.properties" />
<if condition='property("env").equals("dev")'>
<then>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</then>
</if>
</configuration>

View File

@ -0,0 +1,74 @@
package com.stackify.services;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();
@Test
public void testAppenders() {
Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.info("Testing rolling file logger");
MDC.put("userRole", "ADMIN");
Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger");
siftingLogger.info("Admin Action");
}
@Test
public void testLayouts() {
Logger htmlLogger = LoggerFactory.getLogger("htmlLogger");
htmlLogger.error("Employee Information Update Failed");
htmlLogger.info("New Account Created");
Logger colorLogger = LoggerFactory.getLogger("colorLogger");
colorLogger.error("Employee Information Update Failed");
colorLogger.info("New Account Created");
}
@Test
public void testLogLevel() {
ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.setLevel(Level.DEBUG);
rollingFileLogger.debug("Testing Log Level");
}
@Test
public void testParameter() {
Employee employee = new Employee("john@gmail.com", "John", 2000);
if (logger.isDebugEnabled()) {
logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee));
}
logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee));
}
@Test
public void testFilters() {
Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger");
levelFilterLogger.error("Employee Information Update Failed");
Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger");
thresholdFilterLogger.trace("Employee record inserted");
Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger");
evaluatorFilterLogger.debug("Employee account deactivated");
}
@Test
public void testIgnoredLogger() {
Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger");
colorLogger.info("Ignored Log Message");
}
@Test
public void testConditionalConfiguration() {
logger.trace("Employee record updated");
}
}