Saturday 17 October 2015

Log4j2: Substituting Parameters


By using {}, you can substitute variables, objects in log message. Substituting parameters leaves formatting up to you if toString() is not what you want.

package log4j_tutorial;

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

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

 private static class Employee {
  private String firstName;
  private String lastName;
  private double salary;

  public Employee(String firstName, String lastName, double salary) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.salary = salary;
  }

  @Override
  public String toString() {
   StringBuilder builder = new StringBuilder();
   builder.append("Employee [firstName=").append(firstName)
     .append(", lastName=").append(lastName).append(", salary=")
     .append(salary).append("]");
   return builder.toString();
  }

  public String getFirstName() {
   return firstName;
  }

  public String getLastName() {
   return lastName;
  }

  public double getSalary() {
   return salary;
  }

 }

 public static void printData() {
  Employee emp = new Employee("Neelima", "Thokala", 45000.34);

  log.info("Employee {}", emp);
  log.info("firstName {}, lastName {}, salary  {}", emp.getFirstName(),
    emp.getLastName(), emp.getSalary());
 }

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

 }
}


Output
08:53:41.661 [main] INFO  log4j_tutorial.HelloWorld - Employee Employee [firstName=Neelima, lastName=Thokala, salary=45000.34]
08:53:41.661 [main] INFO  log4j_tutorial.HelloWorld - firstName Neelima, lastName Thokala, salary  45000.34




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment