views:

212

answers:

4

We can call Log4j in two ways

1) Having static Logger reference in each class of the package and call logger

2) Having one static Logger reference in once 'static' class and refer this 'static' class from every where

Based on memory which method is efficient and Which method is good generally?

A: 

Creating multiple loggers will take up more memory since the LoggerRepository used for Log4j needs to maintain another logger. But this amount of memory should be insignificant and by having a different logger for each class, you can easily trace where log statements are coming from. You can also turn on different log levels for different packages/classes. I wouldn't recommend having one logger used by all of the classes.

Jeff Storey
+2  A: 

The first method gives you the ability to control (e.g. set the Level of) the logging on a per class basis. This comes at the cost of having lots of Logger instances.

The second method gives you a single Logger instance, but only allows you to control logging for your entire application.

AFAIK, in a long running application, the only ongoing cost of having lots of (static) Logger instances is a small delta in memory usage. So this is a trade-off between a small increase in memory usage and flexibility / configurability of your application's logging.

While I wouldn't go so far as to create a Logger in each and every class, I think that you (or your users/clients) could come to regret it if you used just one Logger in your entire application.

Stephen C
A: 

Obviously method #2 is more memory efficient. Having said that however, it's generally a bad idea to do so. You'll miss out on the per class/package log filtering ability that makes log4j so useful. Unless you are on a really tight memory budget method #1 is really preferred.

There's a 3rd way of calling log4j which is even more memory hungry: use a non-static member in each class. You can use something like: protected Logger log = Logger.getLogger(getClass()); If your class is going to be subclassed this might be preferable, because getClass() always refers to the actual instanced class.

A: 

Keep in mind that Log4j has known issues with eating up PermGen space in certain situations, but generally not over time of a single application instance, which can cause OutOfMemoryError Exceptions.

Where this can be seen most of the time is when your application is deployed to a Java EE application server, on each deployment the static loggers of the last deployment will live on in the ClassLoader. This is only a problem when you re-deploy your application many times without restarting the application server (I mostly have this occur when re-deploying applications all day while developing).

It's usually, and probably a non-issue, but something to be aware of. You can find more information about it by searching for something like "log4j permgen".

Alex