J2EE Log4J Interview Questions
Give an overview of Log4J ?Log4j is a logging framework for Java. Log4J is designed to be fast and flexible. Log4J has 3 main components which work together to enable developers to log messages:
Loggers [was called Category prior to version 1.2]
Logger:The foremost advantage of any logging API like Log4J over plain System.out.println is its ability to disable certain log statements while allowing others to print unhindered. Loggers are hierarchical. The root logger exists at the top of the hierarchy. The root logger always exists and it cannot be retrieved by name. The hierarchical nature of the logger is denoted by "." notation. For example the logger "java.util" is the parent of child logger "java.util.Vector" and so on. Loggers may be assigned priorities such as DEBUG, INFO, WARN, ERROR and FATAL. If a given logger is not assigned a priority, then it inherits the priority from its closest ancestor. The logging requests are made by invoking one of the following printing methods of the logger instance: debug(), info(), warn(), error(), and fatal().
Appenders and Layouts:In addition to selectively enabling and disabling logging requests based on the logger, the Log4J allows logging requests to multiple destinations. In Log4J terms the output destination is an appender.There are appenders for console, files, remote sockets, JMS, etc. One logger can have more than one appender. A logging request for a given logger will be forwarded to all the appenders in that logger plus the other appenders higher in the hierarchy. In addition to the output destination the output format can be categorized as well. This is accomplished by associating layout with an appender. The layout is responsible for formatting the logging request according to userís settings.
Sample configuration file:
XML configuration for Log4j is available, and is usually the best practice. If you have both the log4j.xml and log4j.properties, then log4j.xml takes precedence.
How do you initialize and use Log4J ?
What is the hidden cost of parameter construction when using Log4J ?Do not use in frequently accessed methods or loops:
The above construction has a performance cost in frequently accessed methods and loops in constructing the message parameter, concatenating the String etc regardless of whether the message will be logged or not.
Do use in frequently accessed methods or loops:
The above construction will avoid the parameter construction cost by only constructing the message parameter when you are in debug mode. But it is not a best practice to place log.isDebugEnabled() around all debug code.
J2EE Testing Interview Questions >>>