120 likes | 362 Views
Log4j. Log4j. It is a set of APIs that allows developers to write log statements in their code and configure them externally, using properties files It is possible to enable logging and control its behavior at runtime without modifying the application
E N D
Log4j • It is a set of APIs that allows developers to write log statements in their code and configure them externally, using properties files • It is possible to enable logging and control its behavior at runtime without modifying the application • Open source, The Log4j package is distributed under the Apache Software License.
Very popular – fast and extensible, easy to use. Logging: • Logging equips the developer with detailed context for application failures • Logging is an important component of the development cycle, it provides real context • Logging is persistent – can be saved and evaluated at any time
Components: A logger logs to an appender in a particular layout (style) • Logger - handling the majority of log operations • Appender - controlling the output of log operations • Layout - formatting the output for Appender
Logger: • Takes a request for logging and logs it • Each class in an application can have an individual logger or a common logger • The behaviour of loggers is hierarchical • The ROOT logger resides at the top of the logger hierarchy
Appenders: • The output destination of a logger is called an appender • Appenders handle log output • Many appenders available • Log4j allows logging requests to print to multiple destinations, that • means more than one appender can be attached to a logger • It is also possible to log asynchronously 5 levels of Logger: • DEBUG , INFO , WARN , ERROR , FATAL.
Layout: • To manage the Output. • The most popular layouts are the PatternLayout and HTMLLayout. 1.public class Logger- 2. public interface Appender 3. public abstract class Layout
Configuration: • The log4j environment is fully configurable programmatically. • It is more flexible to configure log4j using configuration files • configuration files can be written in: • XML file (DOMConfigurator) • Plain text file (PropertyConfigurator), properties file.
Example import org.apache.log4j.*; public class Demo { static Logger log = Logger.getLogger(Demo.class.getName()); public static void main(String[] args) { BasicConfigurator.configure(); log.info("Starting up..."); log.setLevel(Level.WARN); log.info("This message should not appear!"); try { // Divide by zero. int x = 5; int y = 20 / (5 - x); } catch (Exception e) { log.error("Oops!", e); } } }
Log Output From The Example 0 [main] INFO Demo - Starting up... 10 [main] ERROR Demo - Oops! java.lang.ArithmeticException: / by zero
Advantage: • Control over which logging statements are enabled or disabled • Manage output destinations • Manage output format • DisAdvantage: • It take 5 nanoseconds each time to log a statement or when it is invoked.