Instead of specifying the class name on each class:
log = Logger.getLogger(Foo.class);
log = Logger.getLogger(Bar.class);
log = Logger.getLogger(Test.class);
Will it be OK to use :
log = Logger.getLogger(this.getClass());
What will be the implications?
getLogger(java. lang. String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name.
getLogger() (without passing a name), then it simply will return the root logger which is created at import time (and therefore, it is never new).
Logger Hierarchy is made up of set of LoggerConfig objects with a parent-child relationship. The topmost element in every Logger Hierarchy is the Root Logger. If Log4j2 doesn't find the configuration file, only Root Logger will be used for logging with logging level as ERROR.
It allows for easy configuration of advanced logging best practices such as rolling files, different types of logging output destinations, support for structured logging formats such as JSON or XML, using multiple loggers and filters, and custom log levels.
If you create a subclass, the log messages will get logged to the subclass's logger.
package pkgone;
public class SuperType {
private Logger log = Logger.getLogger(this.getClass());
public void someAction() {
log.info("Doing something");
}
}
.
package pkgtwo;
import pkgone.SuperType;
public class SubType extends SuperType {
// for instances of SubType, the log object in SuperType
// will get initialized with SubType's class object
}
.
// some code somewhere that uses SubType
SubType obj = new SubType();
obj.someAction();
In the above example, "Doing something" will get logged to the pkgtwo.SubType logger instead of pkgone.SuperType logger, which may or may not be what you want.
Try this way to look up a generic class...
private static final Log LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass());
The best part is you can use this method statically.
If you don't want to repeat to make the logger
and want to avoid write a wrong class name, there's @Log of Project Lombok.
If you don't mind using one more library in your project, you can simply add a logger with a simple annotation.
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
@Log
public class LogExample {
public static void main(String... args) {
log.error("Something's wrong here");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With