Guide To Simplified Java Logging using Java Core API
By Angsuman Chakraborty, Gaea News NetworkTuesday, January 17, 2006
Java comes in with a handy logging package (java.util.logging) which eliminates the need to use external logging packages like Log4J. However it still requires some configuration which makes it cumbersome and repetitive to include in every class. You need to choose your Logger, name it, instantiate it etc.
I like simple solutions. Here is a super simple way to easily use java.logging for your logging needs.
You can also use this solution to easily convert all your System.out.println to use java.logging, which provides more information (calling method name, time etc.), granularity and control.
This solution is applicable to JDK 1.5 and beyond only, uses static import.
First include the following line on top of all your Java source files (after package statement, if any):
import static java.util.logging.Logger.global;
This makes the global Logger methods available in your code. So now you can easily log messages like:
global.severe(”This is a severe error”);
global.info(”This is information only”);
You can log exceptions with:
public void throwing(String sourceClass, String sourceMethod, Throwable thrown)
In short all the methods of java.util.logging.Logger are available to you, even from static methods and static context.
Note: Unfortunately you cannot make it even shorter like simply invoking severe() or info(). However you can shorten the name to say l and use l.severe(). This requires declaring a static Logger variable named l which is instantiated with global;
I am extensively using this approach for simple logging needs in my projects.