Wednesday, July 8, 2009

Eliminating unnecessary log4j setup output

When using log4j for logging in your application, you may see a lot of log messages added by log4j when startup of the application which are not required. These will add to noise in your log files.

They will look something like

log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [Myclass] additivity to [false].
log4j: Level value for Myclass is [DEBUG].
log4j: Desired Level sub-class: [org.apache.log4j.Level]
log4j: Myclass level set to DEBUG
log4j: Class name: [org.apache.log4j.ConsoleAppender]
log4j: Setting property [target] to [System.out].
log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
log4j: Setting property [conversionPattern] to [%-5p %m%n].

These are the debug information from the logger itself. If you are using the XML config it looks like this:

log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"
Turn the debug to false.

Difference between ++x and x++ in Java

++x is called pre-increment while x++ is called post-increment.

For Example:

-- Code --

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6

----------


Check JDK Version used to compile a class

If you want to check the JDK version used to compile a class, use the below command

javap -verbose MyClass

Where MyClass is the class file you are checking.


Some example values it will return are

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50

Reading a String line by line

Given a string that isn't too long, What are the ways read it line by line?

Method 1:

BufferedReader reader = new BufferedReader(new StringReader());
reader.readLine();

Method 2:

final String eol = System.getProperty("line.separator");
output = output.substring(output.indexOf(eol + 1));

Method 3:

String[] lines = string.split(System.getProperty("line.separator"));


Method 4:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}