Saturday 17 October 2015

Log4j2: Formatting log messages

You can format log messages using getFormatterLogger method provided by LogManager (or) by using ‘printf’ method of logger.

Using getFormatterLogger
LogManager class provides following static methods to get a formatter logger.

public static Logger getFormatterLogger()
public static Logger getFormatterLogger(final Class<?> clazz)
public static Logger getFormatterLogger(final Object value)
public static Logger getFormatterLogger(final String name)
package log4j_tutorial;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
 private static final Logger log = LogManager.getFormatterLogger();

 public static void printData() {
  String firstName = "Jessi";
  String lastName = "Daniel";
  double salary = 45000;
  
  log.info("firstName is %s", firstName);
  log.info("lastName is %s", lastName);
  log.info("salary is %f", salary);
 }

 public static void main(String args[]){
  printData();
  
 }
}


Output
08:37:47.117 [main] INFO  log4j_tutorial.HelloWorld - firstName is Jessi
08:37:47.118 [main] INFO  log4j_tutorial.HelloWorld - lastName is Daniel
08:37:47.118 [main] INFO  log4j_tutorial.HelloWorld - salary is 45000.000000

You can use the same format strings as Java's Formatter class (java.util.Formatter).

Using printf method of logger
Logger class provides following methods to a formatted message using the specified format string and arguments.

void printf(Level level, Marker marker, String format, Object... params);

void printf(Level level, String format, Object... params);
package log4j_tutorial;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
 private static final Logger log = LogManager.getLogger();

 public static void printData() {
  String firstName = "Jessi";
  String lastName = "Daniel";
  double salary = 45000;

  log.printf(Level.INFO, "firstName is %s", firstName);
  log.printf(Level.INFO, "lastName is %s", lastName);
  log.printf(Level.INFO, "salary is %f", salary);
 }

 public static void main(String args[]) {
  printData();

 }
}


Output
08:42:13.124 [main] INFO  log4j_tutorial.HelloWorld - firstName is Jessi
08:42:13.125 [main] INFO  log4j_tutorial.HelloWorld - lastName is Daniel
08:42:13.126 [main] INFO  log4j_tutorial.HelloWorld - salary is 45000.000000






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment