Saturday, 2 September 2017

Log4j2 java logging example

As developers  we often, create the multiple log statements stating entry and and exit of methods and specially trace back to lot of exception handling lines with statically typed error messages.

Ideal way to handle this kind of tracing should be via built in library methods.
In this case Log4j2 makes it really easy with its api for entry and exit.
Simple example to test your logs in your api.

  static final Logger logger = LogManager.getLogger(AppController.class.getName());
@RequestMapping("/")
public String welcome() {
logger.traceEntry();
callMe();
logger.traceExit();
return "API UP";
}
private void callMe() {
try {
logger.traceEntry();
logger.info("Test info");
logger.debug("Test Debug");
throw new NullPointerException();
} catch (Exception e) {
logger.error("error occurred", e);
}
}

Maven projects just require 2 dependency, try to use the latest.

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>

  </dependency>


Configurations are easy and gives you control to use your logging mechanism based on the packages.
log4j.xml. Quick Tip make sure the pattern is well defined to give you the method name.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level 
%logger{36} %method - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
<logger name="com.dreamz" level="INFO" />
<Root level="ERROR">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>

Adding Log4j2 to the spring mvc xml based config , and just make sure log4j2.xml is on the class path


  <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>
    <scope>provided</scope>
     </dependency>
    <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.8.2</version>
   <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
<scope>provided</scope>
</dependency>

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...