group and cleanup (#3027)
* move security content from spring-security-rest-full * swagger update * move query language to new module * rename spring-security-rest-full to spring-rest-full * group persistence modules * group testing modules * try fix conflict * cleanup * group and cleanup
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
2a85b9c96e
commit
2e5531edd0
19
logging-modules/log-mdc/README.md
Normal file
19
logging-modules/log-mdc/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
### Relevant Articles:
|
||||
- TBD
|
||||
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback)
|
||||
- [Java Logging with Nested Diagnostic Context (NDC)](http://www.baeldung.com/java-logging-ndc-log4j)
|
||||
- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
|
||||
|
||||
### References
|
||||
|
||||
_Log4j MDC_
|
||||
* <https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html>
|
||||
* <http://veerasundar.com/blog/2009/10/log4j-mdc-mapped-diagnostic-context-what-and-why/>
|
||||
|
||||
_Log4j2 MDC_
|
||||
* <https://logging.apache.org/log4j/2.x/manual/thread-context.html>
|
||||
|
||||
_Logback MDC_
|
||||
* <http://logback.qos.ch/manual/mdc.html>
|
||||
|
||||
|
||||
115
logging-modules/log-mdc/pom.xml
Normal file
115
logging-modules/log-mdc/pom.xml
Normal file
@@ -0,0 +1,115 @@
|
||||
<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.baeldung</groupId>
|
||||
<artifactId>log-mdc</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>log-mdc</name>
|
||||
<packaging>war</packaging>
|
||||
<description>tutorial on logging with MDC and NDC</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.library}</version>
|
||||
</dependency>
|
||||
|
||||
<!--log4j dependencies -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--log4j2 dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>${log4j2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--disruptor for log4j2 async logging -->
|
||||
<dependency>
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<version>${disruptor.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- JBoss Logging (bridge) dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.logging</groupId>
|
||||
<artifactId>jboss-logging</artifactId>
|
||||
<version>${jbosslogging.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<springframework.version>4.3.4.RELEASE</springframework.version>
|
||||
<log4j.version>1.2.17</log4j.version>
|
||||
<log4j2.version>2.7</log4j2.version>
|
||||
<disruptor.version>3.3.6</disruptor.version>
|
||||
<jbosslogging.version>3.3.0.Final</jbosslogging.version>
|
||||
<javax.servlet.version>3.1.0</javax.servlet.version>
|
||||
<jackson.library>2.8.5</jackson.library>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||
<warName>logging-service</warName>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<finalName>logging-service</finalName>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = "com.baeldung")
|
||||
public class AppConfiguration extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||
super.onStartup(servletContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { AppConfiguration.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.mdc;
|
||||
|
||||
import static java.lang.Math.floor;
|
||||
import static java.lang.Math.random;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class TransactionFactory {
|
||||
|
||||
private static final String[] NAMES = { "John", "Susan", "Marc", "Samantha" };
|
||||
private static long nextId = 1;
|
||||
|
||||
public Transfer newInstance() {
|
||||
String transactionId = String.valueOf(nextId++);
|
||||
String owner = NAMES[(int) floor(random() * NAMES.length)];
|
||||
long amount = (long) (random() * 1500 + 500);
|
||||
Transfer tx = new Transfer(transactionId, owner, amount);
|
||||
return tx;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.mdc;
|
||||
|
||||
public class Transfer {
|
||||
|
||||
private String transactionId;
|
||||
private String sender;
|
||||
private Long amount;
|
||||
|
||||
public Transfer(String transactionId, String sender, long amount) {
|
||||
this.transactionId = transactionId;
|
||||
this.sender = sender;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
public String getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
public Long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.mdc;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||
|
||||
public class TransferDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
TransactionFactory transactionFactory = new TransactionFactory();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Transfer tx = transactionFactory.newInstance();
|
||||
|
||||
// Runnable task = new Log4JRunnable(tx);
|
||||
// Runnable task = new Log4J2Runnable(tx);
|
||||
Runnable task = new Slf4jRunnable(tx);
|
||||
|
||||
executor.submit(task);
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.mdc;
|
||||
|
||||
/**
|
||||
* A fake transfer service simulating an actual one.
|
||||
*/
|
||||
public abstract class TransferService {
|
||||
|
||||
/** Sample service transferring a given amount of money.
|
||||
* @return {@code true} when the transfer complete successfully, {@code false} otherwise. */
|
||||
public boolean transfer(long amount) {
|
||||
beforeTransfer(amount);
|
||||
// exchange messages with a remote system to transfer the money
|
||||
try {
|
||||
// let's pause randomly to properly simulate an actual system.
|
||||
Thread.sleep((long) (500 + Math.random() * 500));
|
||||
} catch (InterruptedException e) {
|
||||
// should never happen
|
||||
}
|
||||
// let's simulate both failing and successful transfers
|
||||
boolean outcome = Math.random() >= 0.25;
|
||||
afterTransfer(amount, outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
abstract protected void beforeTransfer(long amount);
|
||||
|
||||
abstract protected void afterTransfer(long amount, boolean outcome);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.mdc.log4j;
|
||||
|
||||
import org.apache.log4j.MDC;
|
||||
|
||||
import com.baeldung.mdc.Transfer;
|
||||
|
||||
public class Log4JRunnable implements Runnable {
|
||||
|
||||
private Transfer tx;
|
||||
private static Log4JTransferService log4jBusinessService = new Log4JTransferService();
|
||||
|
||||
public Log4JRunnable(Transfer tx) {
|
||||
this.tx = tx;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
MDC.put("transaction.id", tx.getTransactionId());
|
||||
MDC.put("transaction.owner", tx.getSender());
|
||||
|
||||
log4jBusinessService.transfer(tx.getAmount());
|
||||
|
||||
MDC.clear();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.mdc.log4j;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.baeldung.mdc.TransferService;
|
||||
|
||||
public class Log4JTransferService extends TransferService {
|
||||
|
||||
private Logger logger = Logger.getLogger(Log4JTransferService.class);
|
||||
|
||||
@Override
|
||||
protected void beforeTransfer(long amount) {
|
||||
logger.info("Preparing to transfer " + amount + "$.");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterTransfer(long amount, boolean outcome) {
|
||||
logger.info("Has transfer of " + amount + "$ completed successfully ? " + outcome + ".");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.mdc.log4j2;
|
||||
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
|
||||
import com.baeldung.mdc.Transfer;
|
||||
|
||||
public class Log4J2Runnable implements Runnable {
|
||||
private final Transfer tx;
|
||||
private Log4J2TransferService log4j2BusinessService = new Log4J2TransferService();
|
||||
|
||||
public Log4J2Runnable(Transfer tx) {
|
||||
this.tx = tx;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
ThreadContext.put("transaction.id", tx.getTransactionId());
|
||||
ThreadContext.put("transaction.owner", tx.getSender());
|
||||
|
||||
log4j2BusinessService.transfer(tx.getAmount());
|
||||
|
||||
ThreadContext.clearAll();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.mdc.log4j2;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.baeldung.mdc.TransferService;
|
||||
|
||||
public class Log4J2TransferService extends TransferService {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Override
|
||||
protected void beforeTransfer(long amount) {
|
||||
logger.info("Preparing to transfer {}$.", amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterTransfer(long amount, boolean outcome) {
|
||||
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.mdc.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.mdc.TransferService;
|
||||
|
||||
final class Slf4TransferService extends TransferService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Slf4TransferService.class);
|
||||
|
||||
@Override
|
||||
protected void beforeTransfer(long amount) {
|
||||
logger.info("Preparing to transfer {}$.", amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterTransfer(long amount, boolean outcome) {
|
||||
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.mdc.slf4j;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
|
||||
import com.baeldung.mdc.Transfer;
|
||||
|
||||
public class Slf4jRunnable implements Runnable {
|
||||
private final Transfer tx;
|
||||
|
||||
public Slf4jRunnable(Transfer tx) {
|
||||
this.tx = tx;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
MDC.put("transaction.id", tx.getTransactionId());
|
||||
MDC.put("transaction.owner", tx.getSender());
|
||||
|
||||
new Slf4TransferService().transfer(tx.getAmount());
|
||||
|
||||
MDC.clear();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.ndc;
|
||||
|
||||
public class Investment {
|
||||
private String transactionId;
|
||||
private String owner;
|
||||
private Long amount;
|
||||
|
||||
public Investment() {
|
||||
}
|
||||
|
||||
public Investment(String transactionId, String owner, Long amount) {
|
||||
this.transactionId = transactionId;
|
||||
this.owner = owner;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
public void setTransactionId(String transactionId) {
|
||||
this.transactionId = transactionId;
|
||||
}
|
||||
|
||||
public String getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public void setOwner(String owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public Long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(Long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.ndc.controller;
|
||||
|
||||
import org.jboss.logging.NDC;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.ndc.Investment;
|
||||
import com.baeldung.ndc.service.InvestmentService;
|
||||
|
||||
@RestController
|
||||
public class JBossLoggingController {
|
||||
@Autowired
|
||||
@Qualifier("JBossLoggingInvestmentService")
|
||||
private InvestmentService jbossLoggingBusinessService;
|
||||
|
||||
@RequestMapping(value = "/ndc/jboss-logging", method = RequestMethod.POST)
|
||||
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
|
||||
// Add transactionId and owner to NDC
|
||||
NDC.push("tx.id=" + investment.getTransactionId());
|
||||
NDC.push("tx.owner=" + investment.getOwner());
|
||||
|
||||
try {
|
||||
jbossLoggingBusinessService.transfer(investment.getAmount());
|
||||
} finally {
|
||||
// take out owner from the NDC stack
|
||||
NDC.pop();
|
||||
|
||||
// take out transactionId from the NDC stack
|
||||
NDC.pop();
|
||||
|
||||
NDC.clear();
|
||||
}
|
||||
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.ndc.controller;
|
||||
|
||||
import org.apache.logging.log4j.ThreadContext;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.ndc.Investment;
|
||||
import com.baeldung.ndc.service.InvestmentService;
|
||||
|
||||
@RestController
|
||||
public class Log4J2Controller {
|
||||
@Autowired
|
||||
@Qualifier("log4j2InvestmentService")
|
||||
private InvestmentService log4j2BusinessService;
|
||||
|
||||
@RequestMapping(value = "/ndc/log4j2", method = RequestMethod.POST)
|
||||
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
|
||||
// Add transactionId and owner to NDC
|
||||
ThreadContext.push("tx.id=" + investment.getTransactionId());
|
||||
ThreadContext.push("tx.owner=" + investment.getOwner());
|
||||
|
||||
try {
|
||||
log4j2BusinessService.transfer(investment.getAmount());
|
||||
} finally {
|
||||
// take out owner from the NDC stack
|
||||
ThreadContext.pop();
|
||||
|
||||
// take out transactionId from the NDC stack
|
||||
ThreadContext.pop();
|
||||
|
||||
ThreadContext.clearAll();
|
||||
}
|
||||
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.ndc.controller;
|
||||
|
||||
import org.apache.log4j.NDC;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.ndc.Investment;
|
||||
import com.baeldung.ndc.service.InvestmentService;
|
||||
|
||||
@RestController
|
||||
public class Log4JController {
|
||||
@Autowired
|
||||
@Qualifier("log4jInvestmentService")
|
||||
private InvestmentService log4jBusinessService;
|
||||
|
||||
@RequestMapping(value = "/ndc/log4j", method = RequestMethod.POST)
|
||||
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
|
||||
// Add transactionId and owner to NDC
|
||||
NDC.push("tx.id=" + investment.getTransactionId());
|
||||
NDC.push("tx.owner=" + investment.getOwner());
|
||||
|
||||
try {
|
||||
log4jBusinessService.transfer(investment.getAmount());
|
||||
} finally {
|
||||
// take out owner from the NDC stack
|
||||
NDC.pop();
|
||||
|
||||
// take out transactionId from the NDC stack
|
||||
NDC.pop();
|
||||
|
||||
NDC.remove();
|
||||
}
|
||||
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.ndc.service;
|
||||
|
||||
/**
|
||||
* A fake investment service.
|
||||
*/
|
||||
public interface InvestmentService {
|
||||
|
||||
/**
|
||||
* Sample service transferring a given amount of money.
|
||||
* @param amount
|
||||
* @return {@code true} when the transfer complete successfully, {@code false} otherwise.
|
||||
*/
|
||||
default public boolean transfer(long amount) {
|
||||
beforeTransfer(amount);
|
||||
// exchange messages with a remote system to transfer the money
|
||||
try {
|
||||
// let's pause randomly to properly simulate an actual system.
|
||||
Thread.sleep((long) (500 + Math.random() * 500));
|
||||
} catch (InterruptedException e) {
|
||||
// should never happen
|
||||
}
|
||||
// let's simulate both failing and successful transfers
|
||||
boolean outcome = Math.random() >= 0.25;
|
||||
afterTransfer(amount, outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
void beforeTransfer(long amount);
|
||||
|
||||
void afterTransfer(long amount, boolean outcome);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.ndc.service;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Qualifier("JBossLoggingInvestmentService")
|
||||
public class JBossLoggingInvestmentService implements InvestmentService {
|
||||
private static final Logger logger = Logger.getLogger(JBossLoggingInvestmentService.class);
|
||||
|
||||
@Override
|
||||
public void beforeTransfer(long amount) {
|
||||
logger.infov("Preparing to transfer {0}$.", amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransfer(long amount, boolean outcome) {
|
||||
logger.infov("Has transfer of {0}$ completed successfully ? {1}.", amount, outcome);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.ndc.service;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Qualifier("log4j2InvestmentService")
|
||||
public class Log4J2InvestmentService implements InvestmentService {
|
||||
private static final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Override
|
||||
public void beforeTransfer(long amount) {
|
||||
logger.info("Preparing to transfer {}$.", amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransfer(long amount, boolean outcome) {
|
||||
logger.info("Has transfer of {}$ completed successfully ? {}.", amount, outcome);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.ndc.service;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Qualifier("log4jInvestmentService")
|
||||
public class Log4JInvestmentService implements InvestmentService {
|
||||
private Logger logger = Logger.getLogger(Log4JInvestmentService.class);
|
||||
|
||||
@Override
|
||||
public void beforeTransfer(long amount) {
|
||||
logger.info("Preparing to transfer " + amount + "$.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransfer(long amount, boolean outcome) {
|
||||
logger.info("Has transfer of " + amount + "$ completed successfully ? " + outcome + ".");
|
||||
}
|
||||
}
|
||||
12
logging-modules/log-mdc/src/main/resources/log4j.properties
Normal file
12
logging-modules/log-mdc/src/main/resources/log4j.properties
Normal file
@@ -0,0 +1,12 @@
|
||||
log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
|
||||
|
||||
#note the %X{userName} - this is how you fetch data from Mapped Diagnostic Context (MDC)
|
||||
#log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m%n
|
||||
# %x is used to fetch data from NDC. So below setting uses both MDC and NDC
|
||||
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} %x - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n
|
||||
|
||||
# NDC only setting - %x is used to fetch data from NDC
|
||||
#log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c{1} - %m - [%x]%n
|
||||
|
||||
log4j.rootLogger = INFO, consoleAppender
|
||||
24
logging-modules/log-mdc/src/main/resources/log4j2.xml
Normal file
24
logging-modules/log-mdc/src/main/resources/log4j2.xml
Normal file
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="INFO">
|
||||
<Appenders>
|
||||
<Console name="stdout" target="SYSTEM_OUT">
|
||||
<!-- MDC and NDC -->
|
||||
<PatternLayout
|
||||
pattern="%-4r [%t] %5p %c{1} - %m - %x - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" />
|
||||
<!-- MDC Only -->
|
||||
<!-- <PatternLayout
|
||||
pattern="%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n" /> -->
|
||||
<!-- NDC Only -->
|
||||
<!-- <PatternLayout
|
||||
pattern="%-4r [%t] %5p %c{1} - %m - %x%n" /> -->
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Logger name="com.baeldung.log4j2" level="TRACE" />
|
||||
|
||||
<AsyncRoot level="DEBUG">
|
||||
<AppenderRef ref="stdout" />
|
||||
</AsyncRoot>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
13
logging-modules/log-mdc/src/main/resources/logback.xml
Normal file
13
logging-modules/log-mdc/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<configuration>
|
||||
|
||||
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
|
||||
<pattern>%-4r [%t] %5p %c{1} - %m - tx.id=%X{transaction.id} tx.owner=%X{transaction.owner}%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="TRACE">
|
||||
<appender-ref ref="stdout" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.mdc.log4j;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.mdc.TransactionFactory;
|
||||
import com.baeldung.mdc.Transfer;
|
||||
|
||||
public class DemoIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void main() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
TransactionFactory transactionFactory = new TransactionFactory();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Transfer tx = transactionFactory.newInstance();
|
||||
Runnable task = new Log4JRunnable(tx);
|
||||
executor.submit(task);
|
||||
}
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.mdc.log4j2;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.mdc.TransactionFactory;
|
||||
import com.baeldung.mdc.Transfer;
|
||||
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||
|
||||
public class DemoIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void main() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
TransactionFactory transactionFactory = new TransactionFactory();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Transfer tx = transactionFactory.newInstance();
|
||||
Runnable task = new Log4J2Runnable(tx);
|
||||
executor.submit(task);
|
||||
}
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.mdc.slf4j;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.mdc.TransactionFactory;
|
||||
import com.baeldung.mdc.Transfer;
|
||||
import com.baeldung.mdc.log4j.Log4JRunnable;
|
||||
import com.baeldung.mdc.log4j2.Log4J2Runnable;
|
||||
import com.baeldung.mdc.slf4j.Slf4jRunnable;
|
||||
|
||||
public class DemoIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void main() throws InterruptedException {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||
TransactionFactory transactionFactory = new TransactionFactory();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Transfer tx = transactionFactory.newInstance();
|
||||
Runnable task = new Slf4jRunnable(tx);
|
||||
executor.submit(task);
|
||||
}
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(60, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.ndc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.config.AppConfiguration;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = AppConfiguration.class)
|
||||
@WebAppConfiguration
|
||||
public class NDCLogIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
private Investment investment;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
|
||||
investment = new Investment();
|
||||
investment.setTransactionId("123");
|
||||
investment.setOwner("Mark");
|
||||
investment.setAmount(1000L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLog4jLogger_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
|
||||
mockMvc.perform(post("/ndc/log4j", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLog4j2Logger_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
|
||||
mockMvc.perform(post("/ndc/log4j2", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJBossLoggerBridge_whenNDCAdded_thenResponseOkAndNDCInLog() throws Exception {
|
||||
mockMvc.perform(post("/ndc/jboss-logging", investment).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(investment))).andExpect(status().is2xxSuccessful());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
7
logging-modules/log4j/README.md
Normal file
7
logging-modules/log4j/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro)
|
||||
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
|
||||
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
|
||||
- [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders)
|
||||
56
logging-modules/log4j/pom.xml
Normal file
56
logging-modules/log4j/pom.xml
Normal file
@@ -0,0 +1,56 @@
|
||||
<?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>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!--log4j dependencies -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>apache-log4j-extras</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--log4j2 dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>${log4j-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j-core.version}</version>
|
||||
</dependency>
|
||||
<!--disruptor for log4j2 async logging -->
|
||||
<dependency>
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<version>${disruptor.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<log4j.version>1.2.17</log4j.version>
|
||||
<log4j-api.version>2.7</log4j-api.version>
|
||||
<log4j-core.version>2.7</log4j-core.version>
|
||||
<disruptor.version>3.3.6</disruptor.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.log4j;
|
||||
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class Log4jExample {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Log4jExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.trace("Trace log message");
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.log4j;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class Log4jRollingExample {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Log4jRollingExample.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
for(int i = 0; i<2000; i++){
|
||||
logger.info("This is the " + i + " time I say 'Hello World'.");
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.log4j2;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
public class Log4j2Example {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(Log4j2Example.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.log4j2;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class Log4j2RollingExample {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(Log4j2RollingExample.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
for(int i = 0; i<2000; i++){
|
||||
logger.info("This is the {} time I say 'Hello World'.", i);
|
||||
Thread.sleep(100);
|
||||
}
|
||||
LogManager.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class LogbackExample {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LogbackExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.logback;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class LogbackRollingExample {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LogbackRollingExample.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
for(int i = 0; i<2000; i++){
|
||||
logger.info("This is the {} time I say 'Hello World'.", i);
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml
|
||||
*/
|
||||
public class Slf4jExample {
|
||||
private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
|
||||
String variable = "Hello John";
|
||||
logger.debug("Printing variable value {} ", variable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.slf4j;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class Slf4jRollingExample {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(Slf4jRollingExample.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
for(int i = 0; i<2000; i++){
|
||||
logger.info("This is the {} time I say 'Hello World'.", i);
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
99
logging-modules/log4j/src/main/resources/log4j.xml
Normal file
99
logging-modules/log4j/src/main/resources/log4j.xml
Normal file
@@ -0,0 +1,99 @@
|
||||
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
|
||||
<log4j:configuration debug="false">
|
||||
|
||||
<!--Console appender -->
|
||||
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!-- File appender -->
|
||||
<appender name="fout" class="org.apache.log4j.FileAppender">
|
||||
<param name="file" value="log4j/target/baeldung-log4j.log"/>
|
||||
<param name="append" value="false"/>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!-- Rolling appenders -->
|
||||
<appender name="roll-by-size" class="org.apache.log4j.RollingFileAppender">
|
||||
<param name="file" value="target/log4j/roll-by-size/app.log"/>
|
||||
<param name="MaxFileSize" value="5KB"/>
|
||||
<param name="MaxBackupIndex" value="2"/> <!-- It's one by default. -->
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="roll-by-size-2" class="org.apache.log4j.RollingFileAppender">
|
||||
<param name="file" value="target/log4j/roll-by-size-2/app.log"/>
|
||||
<param name="MaxFileSize" value="5KB"/>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="roll-by-window"
|
||||
class="org.apache.log4j.rolling.RollingFileAppender">
|
||||
<rollingPolicy
|
||||
class="org.apache.log4j.rolling.FixedWindowRollingPolicy">
|
||||
<param name="ActiveFileName" value="target/log4j/roll-by-window/app.log"/>
|
||||
<param name="FileNamePattern"
|
||||
value="target/log4j/roll-by-window/app.%i.log.gz"/>
|
||||
<param name="MinIndex" value="7"/>
|
||||
<param name="MaxIndex" value="17"/>
|
||||
</rollingPolicy>
|
||||
<triggeringPolicy
|
||||
class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
|
||||
<param name="MaxFileSize" value="50000"/>
|
||||
</triggeringPolicy>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="roll-by-time"
|
||||
class="org.apache.log4j.rolling.RollingFileAppender">
|
||||
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
|
||||
<param name="FileNamePattern"
|
||||
value="target/log4j/roll-by-time/app.%d{HH-mm}.log.gz"/>
|
||||
</rollingPolicy>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="roll-by-time-and-size"
|
||||
class="org.apache.log4j.rolling.RollingFileAppender">
|
||||
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
|
||||
<param name="FileNamePattern"
|
||||
value="target/log4j/roll-by-time-and-size/app.%d{HH-mm}.%i.log.gz"/>
|
||||
</rollingPolicy>
|
||||
<triggeringPolicy
|
||||
class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
|
||||
<param name="MaxFileSize" value="50000"/>
|
||||
</triggeringPolicy>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!--Override log level for specified package -->
|
||||
<category name="com.baeldung.log4j">
|
||||
<priority value="TRACE"/>
|
||||
</category>
|
||||
|
||||
<category name="com.baeldung.log4j.Log4jRollingExample">
|
||||
<priority value="TRACE"/>
|
||||
<appender-ref ref="roll-by-size"/>
|
||||
<appender-ref ref="roll-by-size-2"/>
|
||||
<appender-ref ref="roll-by-window"/>
|
||||
<appender-ref ref="roll-by-time"/>
|
||||
<appender-ref ref="roll-by-time-and-size"/>
|
||||
</category>
|
||||
|
||||
<root>
|
||||
<level value="DEBUG"/>
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="fout"/>
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
||||
80
logging-modules/log4j/src/main/resources/log4j2.xml
Normal file
80
logging-modules/log4j/src/main/resources/log4j2.xml
Normal file
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="INFO">
|
||||
<Appenders>
|
||||
# Console appender
|
||||
<Console name="stdout" target="SYSTEM_OUT">
|
||||
# Pattern of log message for console appender
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</Console>
|
||||
|
||||
# File appender
|
||||
<File name="fout" fileName="log4j/target/baeldung-log4j2.log"
|
||||
immediateFlush="false" append="false">
|
||||
# Pattern of log message for file appender
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</File>
|
||||
|
||||
# Rolling appender
|
||||
<RollingFile name="roll-by-size"
|
||||
fileName="target/log4j2/roll-by-size/app.log" filePattern="target/log4j2/roll-by-size/app.%i.log.gz"
|
||||
ignoreExceptions="false">
|
||||
<PatternLayout>
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
|
||||
</PatternLayout>
|
||||
<Policies>
|
||||
<OnStartupTriggeringPolicy/>
|
||||
<SizeBasedTriggeringPolicy
|
||||
size="5 KB"/>
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
|
||||
<RollingFile name="roll-by-time"
|
||||
fileName="target/log4j2/roll-by-time/app.log"
|
||||
filePattern="target/log4j2/roll-by-time/app.%d{MM-dd-yyyy-HH-mm}.log.gz"
|
||||
ignoreExceptions="false">
|
||||
<PatternLayout>
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
|
||||
</PatternLayout>
|
||||
<TimeBasedTriggeringPolicy/>
|
||||
</RollingFile>
|
||||
|
||||
<RollingFile name="roll-by-time-and-size"
|
||||
fileName="target/log4j2/roll-by-time-and-size/app.log"
|
||||
filePattern="target/log4j2/roll-by-time-and-size/app.%d{MM-dd-yyyy-HH-mm}.%i.log.gz"
|
||||
ignoreExceptions="false">
|
||||
<PatternLayout>
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
|
||||
</PatternLayout>
|
||||
<Policies>
|
||||
<OnStartupTriggeringPolicy/>
|
||||
<SizeBasedTriggeringPolicy
|
||||
size="5 KB"/>
|
||||
<TimeBasedTriggeringPolicy/>
|
||||
</Policies>
|
||||
<DefaultRolloverStrategy>
|
||||
<Delete basePath="${baseDir}" maxDepth="2">
|
||||
<IfFileName
|
||||
glob="target/log4j2/roll-by-time-and-size/app.*.log.gz"/>
|
||||
<IfLastModified age="20s"/>
|
||||
</Delete>
|
||||
</DefaultRolloverStrategy>
|
||||
</RollingFile>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
# Override log level for specified package
|
||||
<Logger name="com.baeldung.log4j2" level="TRACE"/>
|
||||
|
||||
<Logger name="com.baeldung.log4j2.Log4j2RollingExample"
|
||||
level="TRACE">
|
||||
<AppenderRef ref="roll-by-size"/>
|
||||
<AppenderRef ref="roll-by-time"/>
|
||||
<AppenderRef ref="roll-by-time-and-size"/>
|
||||
</Logger>
|
||||
|
||||
<AsyncRoot level="DEBUG">
|
||||
<AppenderRef ref="stdout"/>
|
||||
<AppenderRef ref="fout"/>
|
||||
</AsyncRoot>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
85
logging-modules/log4j/src/main/resources/logback.xml
Normal file
85
logging-modules/log4j/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,85 @@
|
||||
<configuration>
|
||||
# Console appender
|
||||
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
# Pattern of log message for console appender
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
# File appender
|
||||
<appender name="fout" class="ch.qos.logback.core.FileAppender">
|
||||
# Name of a log file
|
||||
<file>log4j/target/baeldung-logback.log</file>
|
||||
<append>false</append>
|
||||
<encoder>
|
||||
# Pattern of log message for file appender
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
# Rolling appenders
|
||||
<appender name="roll-by-size"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>target/slf4j/roll-by-size/app.log</file>
|
||||
<rollingPolicy
|
||||
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
|
||||
<fileNamePattern>target/slf4j/roll-by-size/app.%i.log.zip
|
||||
</fileNamePattern>
|
||||
<minIndex>1</minIndex>
|
||||
<maxIndex>3</maxIndex>
|
||||
<totalSizeCap>1MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<triggeringPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
|
||||
<maxFileSize>5KB</maxFileSize>
|
||||
</triggeringPolicy>
|
||||
<encoder>
|
||||
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="roll-by-time"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>target/slf4j/roll-by-time/app.log</file>
|
||||
<rollingPolicy
|
||||
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>target/slf4j/roll-by-time/app.%d{yyyy-MM-dd-HH-mm}.log.zip
|
||||
</fileNamePattern>
|
||||
<maxHistory>20</maxHistory>
|
||||
<totalSizeCap>1MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="roll-by-time-and-size"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>target/slf4j/roll-by-time-and-size/app.log</file>
|
||||
<rollingPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>target/slf4j/roll-by-time-and-size/app.%d{yyyy-MM-dd-mm}.%i.log.zip
|
||||
</fileNamePattern>
|
||||
<maxFileSize>5KB</maxFileSize>
|
||||
<maxHistory>20</maxHistory>
|
||||
<totalSizeCap>1MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
# Override log level for specified package
|
||||
<logger name="com.baeldung.slf4j.Slf4jRollingExample" level="TRACE">
|
||||
<appender-ref ref="roll-by-size"/>
|
||||
<appender-ref ref="roll-by-time"/>
|
||||
<appender-ref ref="roll-by-time-and-size"/>
|
||||
</logger>
|
||||
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="fout"/>
|
||||
</root>
|
||||
</configuration>
|
||||
4
logging-modules/log4j2/README.md
Normal file
4
logging-modules/log4j2/README.md
Normal file
@@ -0,0 +1,4 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Intro to Log4j2 – Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters)
|
||||
- [Log4j 2 and Lambda Expressions](http://www.baeldung.com/log4j-2-lazy-logging)
|
||||
68
logging-modules/log4j2/pom.xml
Normal file
68
logging-modules/log4j2/pom.xml
Normal file
@@ -0,0 +1,68 @@
|
||||
<?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>${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 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 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>
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
||||
<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>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,130 @@
|
||||
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 CustomLoggingIntegrationTest {
|
||||
|
||||
@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_whenLogToConsole_thanOK() 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_whenLogToConsoleInColors_thanOK() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
|
||||
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.");
|
||||
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_whenFilterByMarker_thanOK() throws Exception {
|
||||
Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER");
|
||||
Marker appError = MarkerManager.getMarker("APP_ERROR");
|
||||
Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE");
|
||||
|
||||
logger.error(appError, "This marker message at ERROR level should be hidden.");
|
||||
logger.trace(connectionTrace, "This is a marker message at TRACE level.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggerWithConsoleConfig_whenFilterByThreadContext_thanOK() 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_whenLogToJsonFile_thanOK() 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_whenLog_thanOK() throws Exception {
|
||||
Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER");
|
||||
Exception e = new RuntimeException("This is only a test!");
|
||||
|
||||
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.");
|
||||
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_whenLogToDataSource_thanOK() 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_whenLogToXMLFile_thanOK() 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.logging.log4j2.tests;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LambdaExpressionsIntegrationTest {
|
||||
|
||||
private static final Logger logger = LogManager.getRootLogger();
|
||||
|
||||
@Test
|
||||
public void whenCheckLogMessage_thenOk() {
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace("Numer is {}", getRandomNumber());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseLambdaExpression_thenOk() {
|
||||
logger.trace("Number is {}", () -> getRandomNumber());
|
||||
logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber());
|
||||
}
|
||||
|
||||
private int getRandomNumber() {
|
||||
return (new Random()).nextInt(10);
|
||||
}
|
||||
|
||||
private String getName() {
|
||||
return "John";
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +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" />
|
||||
</Console>
|
||||
73
logging-modules/log4j2/src/test/resources/log4j2.xml
Normal file
73
logging-modules/log4j2/src/test/resources/log4j2.xml
Normal file
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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" />
|
||||
</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" mdcId="mdc" includeMDC="true" />
|
||||
<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>
|
||||
<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>
|
||||
Reference in New Issue
Block a user