How to Reverse Number?


Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;

      System.out.println("Enter the integer number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();

      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }

      System.out.println("Reverse of entered integer number is "+reverse);
   }
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Java, Algorithm, Programming Test | Tagged , , | Leave a comment

How to Prints Alphabets by Java Loops


Here you will see, How to prints Alphabets through Java all loops (for, While and do while). In these loops we are just increments char value and characters are increment continuously.

public class PrintAlphabets {

	public static void main(String[] args) {
		// By for Loop
		char ch;
		for (ch = 'a'; ch <= 'z'; ch++) {
			System.out.print(ch + " ");
		}
		System.out.println();

		// By While loop
		char c = 'a';

		while (c <= 'z') {
			System.out.print(c + " ");
			c++;
		}
		System.out.println();

		// By do while loop
		c = 'A';

		do {
			System.out.print(c + " ");
			c++;
		} while (c <= 'Z');
	}

}

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Java, Algorithm, Data Structure, Programming Test | Tagged , , , , | Leave a comment

Frequently Asked Algorithms and Programs in Interviews


Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level also in IT.

Posted in Algorithm, Data Structure, Java, Programming Test | 7 Comments

How to Swap two Numbers with and with out temporary variable.


Here I will show you how you can swap two numbers A=20 and B=10 with and without temporary variables as A=10 and B=20.

Swap Numbers with Temporary Variable

I will take one more temporary variable as temp to keep value of B so that during  copy of value A to B value of B is in temp and now we can copy value of temp to A. As below

temp=B       (This state : A=20, B=10, temp=10)

B=A;            (This state : A=20, B=20, temp=10)

A=temp      (This state : A=10, B=20, temp=10)

By applying above logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers without Temporary Variable

There are two ways two swap two numbers without using any temporary variable.

Addition and Subtraction

Here you will see how to swap numbers A=20 and B=10 by using addition and subtraction operations.

A=A+B           (This state : A=30, B=10)

B=A-B           (This state : A=30, B=20)

A=A-B           (This state : A=10, B=20)

By applying above addition and subtraction logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Multiplication and Division

Here you will see how to swap numbers A=20 and B=10 by using multiplication and division operations.

A=A*B           (This state : A=200, B=10)

B=A/B           (This state : A=200, B=20)

A=A/B           (This state : A=10, B=20)

By applying above multiplication and division logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers Java Program

package test;

import java.util.Scanner;

public class SwapNumbers {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Please Enter First Number");
		int A=scan.nextInt();

		System.out.println("Please Enter Second Number");
		int B=scan.nextInt();

		//swap Numbers with temporary variable
		swapNumbersWithTemp(A,B);
		//swap Numbers without temporary variable : Add and Sub
		swapNumbersWithoutTempAddSub(A,B);
		//swap Numbers without temporary variable : Mul and Div
		swapNumbersWithoutTempMulDiv(A,B);
	}

	private static void swapNumbersWithTemp(int A, int B)
	{
		int temp=B;
		B=A;
		A=temp;

		System.out.println("Numbers after swap with temporary variables");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempAddSub(int A, int B)
	{
		A=A+B;
		B=A-B;
		A=A-B;

		System.out.println("Numbers after swap without temporary variables: Add and Sub operation");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempMulDiv(int A, int B)
	{
		A=A*B;
		B=A/B;
		A=A/B;

		System.out.println("Numbers after swap without temporary variables: MUl and Div operation");
		System.out.println("A="+A+"and B="+B);
	}

}

Output

Please Enter First Number
20
Please Enter Second Number
10
Numbers after swap with temporary variables
A=10and B=20
Numbers after swap without temporary variables: Add and Sub operation
A=10and B=20
Numbers after swap without temporary variables: MUl and Div operation
A=10and B=20
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 			

 

 

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Posted in Algorithm, Data Structure, Java, Programming Test, Uncategorized | Tagged , , , , , | 1 Comment

How to exclude fields from JSON while parsing by GSON/GsonBuilder?


In below previous exaxmples. We discussed about to convert JAVA object to/ from to JSON and pretty formatting and null serailization of fields for JSON conversion. Now here we discussed about how to exclude fields/object while converting to JSON.

How to convert Java object to / from JSON by (GSON)

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

GSON provide two ways to exclude fields from JSON by GsonBuilder:

  • @Expose Annotation
  • Custom Annotation

@Expose Annotation

By using the @Expose annotations and then using the excludeFieldsWithoutExposeAnnotation() method on the GsonBuilder will ignore all fields except the ones that have been exposed using the @Expose annotation.

Custom Annotation

By defining a custom annotation and ignoring fields that are annotated with exclusion class by extending ExclusionStrategy interface implementing that by using below GsonBuilder methods can ingnore/exclude fields from JSON.

Boolean shouldSkipField(FieldAttributes f);

public boolean shouldSkipClass(Class clazz);

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

In below example fields middleName,educationDetail and experienceDetail will not serialize because not having @Expose annotation on it and field country will also not serialize because of having @Country annotation. Here you will see how to unsearilize all these

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.AlbumImages;
import model.Albums;
import model.Country;
import model.Dataset;
import model.Employee;
import util.CustomExclusionStrategy;

class GsonConvertJavaObjectToJSONExclusion {

	public static void main(String[] args) {
		Employee employee= getJavaObject();
		//CustomExclusionStrategy that will exclude the Country field.
// We also allow only those fields that have been exposed using the @Expose
//annotation

				Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.serializeNulls()
				.setExclusionStrategies(new CustomExclusionStrategy(Country.class))
				.excludeFieldsWithoutExposeAnnotation()
				.create();

		System.out.println(gson.toJson(employee));

	}

	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

package util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

import model.Country;
import model.Dataset;

/**
 * This class use custom exclusion policy. We want to ignore all fields that
 * have been annotated with the Country annotation. Note that we can also ignore
 * fields based on name or type. This same type policy can be applied to any *  class.
 *
 */
public class CustomExclusionStrategy implements ExclusionStrategy {

	private Class classToExclude;

	public CustomExclusionStrategy(Class classToExclude) {
		this.classToExclude = classToExclude;
	}

	// This method is called for all fields. if the method returns false the
	// field is excluded from serialization
	//@Override
	public boolean shouldSkipField(FieldAttributes f) {
		if (f.getAnnotation(Country.class) == null)
			return false;

		return true;
	}

	// This method is called for all classes. If the method returns false the class is excluded.
	//@Override
	public boolean shouldSkipClass(Class<?> clazz) {
		if (clazz.equals(classToExclude))
			return true;
		return false;
	}

}
package model;

import java.util.List;
import java.util.Set;

import com.google.gson.annotations.Expose;

public class Employee {
	@Expose
	private String employeeId;
	@Expose
	private String firstName;
	private String middleName;
	@Expose
	private String lastName;
	@Expose
	private String designation;
	private int salary;
	@Expose
	private String permanentAddress;
	private String mailingAddress;
	@Country
	private String country;
	@Expose
	private String mobile;
	private Set<Education> educationDetail;
	private List<Experience> expericeDetail;

	@Override
	public String toString() {
		return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
				+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary
				+ ", permanentAddress=" + permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile
				+ ", educationDetail=" + educationDetail + ", expericeDetail=" + expericeDetail + "]";
	}

	public Employee(String employeeId, String firstName, String middleName, String lastName, String designation,
			int salary, String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
			List<Experience> expericeDetail) {
		super();
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.designation = designation;
		this.salary = salary;
		this.permanentAddress = permanentAddress;
		this.mailingAddress = mailingAddress;
		this.mobile = mobile;
		this.educationDetail = educationDetail;
		this.expericeDetail = expericeDetail;
	}
//Getter and setter of fields
	}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output

{
  "employeeId": "C123",
  "firstName": "Saurabh",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "permanentAddress": "Alpharetta,GA",
  "mobile": "1231231230"
}

Here in above JSON output for Employee class fields middleName, educationDetail and experienceDetail not printed because @Expose annotation was not given on that and by using CustomExlusionStartegy skiping serialization for fields country because it’s having @Country annotation as we remove in class for serialization CustomExclusionStrategy for @Country annotation.

Now in next example will discuss about.

How to parse JSON data token by token by using GSON/JsonToken/JsonReader?

Posted in GSON, JSON, Uncategorized | Tagged , , , , , , , | 1 Comment

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)


In previous example use GSON comes with simple JAVA API’s to convert JAVA object to/from JSON and here I will use GsonBuilder to print format JSON and serialize null object values also.

How to convert Java object to / from JSON by (GSON)

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

  • GsonBuilder().setPrettyPrinting() :  This api is to generate pretty formatted JSON string.
  • GsonBuilder().searializeNulls() :  This api is to serialize null values in object.
  • GsonBuilder().create(): This api is to create GSON object to Java object to/from JSON.
package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON
{
  "employeeId": "C123",
  "firstName": "Saurabh",
  "middleName": "Kumar",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "salary": 50000,
  "permanentAddress": "Alpharetta,GA",
  "mailingAddress": "Dallas, TX",
  "mobile": "1231231230",
  "educationDetail": null,
  "expericeDetail": null
}
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
Convert JSON To Java Object
Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is pretty formatted properly and  serialize null objects for education and experience. In next blog will explain about how to exclude fields while serializing/deserializing to/from JSON by GsonBuilder.

How to exclude fields from JSON while parsing by GSON/GsonBuilder?

Posted in GSON, JSON, Uncategorized | Tagged , , , , , , | 2 Comments

How to convert Java object to / from JSON by (GSON)


GSON comes with simple JAVA API’s toJson()/fromJson() to convert JAVA object to/from JSON. Below is very simple example to convert Employee Java object to JSON and Vice versa. To know more about GSON follow the link GSON Introduction.

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </dependency>

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		Gson gson = new Gson();
		<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON

{"employeeId":"C123","firstName":"Saurabh","middleName":"Kumar","lastName":"Gupta","designation":"Tech Lead","salary":50000,"permanentAddress":"Alpharetta,GA","mailingAddress":"Dallas, TX","mobile":"1231231230"}

Convert JSON To Java Object

Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is not formatted properly and not serialize null objects for education and experience. In next blog will explain about how to format JSON and serialize null values by using GsonBuilder.

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

Posted in GSON, JSON | Tagged , , , | 2 Comments

GSON Introduction


Gson is an open source Java library to serialize and de-serialize Java objects to/from JSON. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code.

Initial Release : May 22,2008
Written in: Java
Developed By: Google
Stable Release : 2.8.2 in 19 Sep, 2017
License: Apache License 2.0

Why GSON is Popular?

  • provide simple methods toJson() and fromJson() to convert Java objects to JSON and vice-versa.
  • Extensive support of Java Generics.
  • allow custom representaion of objects.
  • allow pre-existing unmodifiable objects to be converted to and from JSON.
  • support for complex objects with generic types and having deep inheritance.

Configuration/Dependency

Below dependency required to configure GSON in your application

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
Posted in GSON, JSON, Uncategorized | 1 Comment

Log4j2 JSON Configuration for Java Logging Severity Levels, Formatting and Appenders


In below previous post you read about Log4j2 XML configuration for Appenders, formatters and Loggers for Console and File Logging. I have also explained about RollingFile appeneders and there management.

Below is Log4j2 JSON configuration equivalent to XML configuration and dependency required for JSON. For more info in detail and configuration steps follow previous post for Log4J2 XML configuration.

You have to add below JSON dependency in your class path or pom.xml

POM.XML

<!-- basic Log4j2 dependency -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.6.1</version>
</dependency>
<!-- Asynchronous logging for multithreaded env -->
<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.3.4</version>
</dependency>

<!-- Jackson JSON Processor -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.1</version>
    </dependency>

create file log4j2.json in your root folder or resource folder.

{
   "configuration": {
       "status": "info",
       "monitorInterval": "60",
       "name": "FacingIssuesOnIT",
      "properties": {
         "property": [
            {
               "name": "filename",
               "value": "target/FacingIssueOnIT.log"
            },
            {
               "name": "log-path",
               "value": "C:/logs/"
            }
         ]
      },
      "appenders": {
         "Console": {
            "PatternLayout": {
               "pattern": "%d{yyyyMMdd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
            },
            "name": "STDOUT",
            "target": "SYSTEM_OUT"
         },
         "File": {
            "PatternLayout": {
               "pattern": "%d %p %c{1.} [%t] %m%n"
            },
            "name": "file",
            "fileName": "${filename}"
         },
         "RollingFile": {
            "PatternLayout": {
               "pattern": "%d{yyyyMMdd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
            },

                "Policies": {
               "SizeBasedTriggeringPolicy": {
                  "size": "100 MB"
               },
               "TimeBasedTriggeringPolicy": {
                  "interval": "1",
                  "modulate": "true"
               }
            },
            "DefaultRolloverStrategy": {
               "Delete": {
                  "IfFileName": {
                     "glob": "*/FacingIssueOnIT-*.log.gz"
                  },
                  "IfLastModified": {
                     "age": "1h"
                  },
                  "basePath": "${log-path}",
                  "maxDepth": "2"
               }
            },
            "name": "RollingFile",
            "fileName": "${log-path}/FacingIssueOnIT.log",
            "filePattern": "${log-path}/$${date:yyyy-MM-dd}/FacingIssueOnIT-%d{yyyy-MM-dd}-%i.log.gz"
         }
      },
      "Loggers": {
         "Logger": [
            {
               "name": "com.logging",
               "level": "debug"
            },
            {
               "appender-ref": {
                  "ref": "RollingFile",
                  "level": "debug"
               },
               "name": "root",
               "level": "debug",
               "additivity": "false"
            }
         ],
         "Root": {
            "AppenderRef": [
               {
                  "ref": "file",
                  "level": "error"
               },
               {
                  "ref": "STDOUT",
                  "level": "debug"
               },
               {
                  "ref": "RollingFile"
               }
            ],
            "level": "trace"
         }
      }

   }
}
Posted in Centralize logging, Java Logging, LOG4J2, Logstash | Tagged , , , , | 1 Comment

Log4j2 New Features,Compare with Log4j and other Logging Framework


Log4j2 New Features

  • Java 8-style lambda support for lazy logging.
  • Log4j2 is garbage-free or least low-garbage since version 2.6
  • Log4j2 support configuration via XML, JSON, YAML, properties configuration files or programmatically.
  • Async Loggers – performance similar to logging switched off on multithreaded.
  • Concurrency improvements: log4j2 uses java.util.concurrent libraries to perform locking at the lowest level possible. Log4j-1.x has known deadlock issues.
  • Filtering: filtering based on context data,  regular expressions, markers and other components in the Log event. Filters can be associated with Loggers. You can use a common Filter class in any of these circumstances.
  • Custom Log Level
  • Plugin Architecture – easy to extend by building custom components
    Supported APIs: SLF4J, Commons Logging, Log4j-1.x and java.util.logging.

Why people are moving?

  • Community support: Log4j2 has an active community where question, answered, features are added and bugs are fixed.
  • Automatically reload it’s configuration upon modification without losing log events while reconfiguring.

Drawback

  • log4j 2.0 is very different than log4j 1.x, and the API is mostly incompatible.
  • Java 6 required for version 2.0 to 2.3. Java 7 is required for Log4j 2.4 and later.

Steps to upgrade Log4j1 to Log4j2

  1. add log4j2 dependency  log4j-api-2.6.2.jar and log4j-core-2.6.2.jar in your class path or pom.xml .
  2. Log4j2 looks for file log4j2.xml in config file. Add log4j2.xml file either in the class path or specify path with log4j configuration file system properties.
  3. To debug the log4j.xml configuration use in the beginning of configuration file.
  4. To add more configuration for Console, File and RollingFile appenders follow Log4j2 Tutorial and Configuration.

Comparison with other Logging Framework

Follow the below link to compare different logging framework on benchmark.

https://www.loggly.com/blog/benchmarking-java-logging-frameworks/

Posted in Java, Java Logging, LOG4J2 | Tagged , , , , , , ,