Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Logging - Wrapper?

Tags:

java

logging

I am starting with a new Project and have done some considerations about logging. I always used the pattern where every class, in which logging is done, has its own static Logger:

private static final Logger logger = Logger.getLogger(LoggingInterceptor.class);

I do not really like this approach as I have to copy this line into every class where I will log something. I considered using the Android approach where there is the Log class with it's static methods to log. I started searching on the internet for a similar approach done by someone else, but did not find anything.

So my question is: What could be disatvantages of this approach?

I cannot think of any but rather of some advantages, as it follows the DRY pattern. The different categories could be handled as in Android with 'tags', which are parameters of the static Log methods. For example:

 Log.debug(tag, message, exception);

The Log class itself would then use a common Logging Framework such as Log4j or even SLF4J.

So I am interested in your opinions.

like image 920
homedom Avatar asked Apr 24 '15 17:04

homedom


1 Answers

Based on the java.util.logging.Logger API and this article, the main reason for getLogger() is to ensure the same Logger and Handler set are used independently between subsystems.

Java's recommended solution is to obtain the Logger at the top of each file, and then log to that object every time you need to.

Using a static Log.debug would require tag to be processed each time so that the correct Handler set was being used. Thus, it would be less efficient than having the Log object ready to go.

However, if you are not using handlers, or not differentiating between subsystems, then static functions would be a reasonable shortcut, so long as the library used suited your needs.

like image 80
Wasmoo Avatar answered Sep 23 '22 10:09

Wasmoo