Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to create loggers per class?

Many forums and stackoverflow questions suggest that the recommended approach for creating loggers is to create them per class.

A quick look at the Log4j's Logger getLogger(String name) implementation suggests that, all the loggers are stored in a static map.

I wonder if we have thousands of classes in an application and a logger is defined in each class, wouldn't it cause memory/performance issues.

Alternatively, why cant we define some standard loggers (based on some functional criteria) in the application and have the developers use them in the classes. I understand that having a separate logger allows us to change its logging level, but I believe its not big issue if there are sufficient predefined loggers.

I looked at the questions Is a logger per class or is a set of loggers that are accessed by the entire application perferred? and Log4J: Strategies for creating Logger instances but they dont seem to cover this topic.

like image 981
Naresh Vavilala Avatar asked Sep 12 '14 21:09

Naresh Vavilala


People also ask

What is the purpose of creating a 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.

Why do we need logging in Java?

Java provides the ability to capture the log files. There are multiple reasons why we may need to capture the application activity.

Why do we use Logger instead of system out Println?

If you are running a Java program in Linux or any UNIX-based system, Log4j or SLF4j or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System. out. println() statement.


1 Answers

You don't have to, it's just easier to manage. Loggers follow parent-child relationship. Children pretty much inherit everything from their parents. This way you can define very specific logging behavior or have it inherited generically.

Alternatively, why cant we define some standard loggers (based on some functional criteria) in the application and have the developers use them in the classes. I understand that having a separate logger allows us to change its logging level, but I believe it's not big issue if there are sufficient predefined loggers.

This would require some pretty intense dependency injection to make those loggers available to every type, also potentially adding an extra dependency.

like image 75
Sotirios Delimanolis Avatar answered Sep 19 '22 07:09

Sotirios Delimanolis