Why log4j's Logger.getLogger() need pass a Class type?

  1. You can always use any string as logger name other than class type. It's definitely ok.

  2. The reason why many people use class type, I guess:

    • Easy to use. You don't need to worry about logger name duplication in a complex Java EE application. If other people also use your logger name, you may have a log file including no only the output of your class;

    • Easy to check the logging class, as the logger name will show in the log file. You can quickly navigate to the specific class;

    • When you distribute you class, people may want to redirect the logging from your class to a specific file or somewhere else. In such case, if you use a special logger name, we may need to check the source code or imposssible to do that if souce is unavailable.


From the javadoc: Logger.getLogger(Class) is a shorthand for getLogger(clazz.getName()). A convention used with log4j and other logging frameworks is to define a static logger per class. For example,

public class SomeClass {
    private static final Logger LOG = Logger.getLogger(SomeClass.class);
    ...
}

I have found this convention to work well for organizing logging output. It's certainly not required but is a useful practice.


1:you can use "class name" or "string name" when you define in log4j.properties before, such as

log4j.logger.anything=INFO,anything

so,you can record your log as

 Logger logger = Logger.getLogger("anything");

2:If you define some log name,you can check it easily,cus they are separate.

Tags:

Java

Log4J