Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cons for defining logger non-static

Tags:

java

logging

Comments for this answer How do you reduce Java logging boilerplate code? strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:
1) superclass logs with the subclass's logger
2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

like image 393
martsraits Avatar asked Jan 14 '09 17:01

martsraits


People also ask

Does logger need to be static?

Loggers should be declared to be static and final. It is good programming practice to share a single logger object between all of the instances of a particular class and to use the same logger for the duration of the program.

Does logging decrease performance?

Short answer: yes, it decreases application performance as it uses some CPU cycles and other resources (memory, etc). Show activity on this post. Logging can be 30% of you cpu time or more.

Does logging slow down application?

It will slow down your application (obviously) but it depends a lot on your application if the slow down qualifies as "serious". I think you need to let it run and then decide if the performance is acceptable...

Why do we use logger?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.


2 Answers

If your Logger is an instance member instead of static, the Logger has to be retrieved every time a new object is created. Albeit this overhead is probably insignificant, but it's one disadvantage.

From a design perspective, Loggers aren't really a property of an object, since they're usually meta-information about your system rather than business information within the system itself. A Logger isn't really part of something like a Car object in the same way an Engine or a Transmission is. Tying Loggers to objects as members (in most cases) doesn't make sense semantically more than anything.

like image 196
Rob Hruska Avatar answered Oct 27 '22 05:10

Rob Hruska


You might want to have a look at these pages discussing the subject:

  • SLF4j FAQ: Should Logger members of a class be declared as static?
  • Commons Wiki: When Static References to Log objects can be used
like image 36
T-Bull Avatar answered Oct 27 '22 05:10

T-Bull