import org.apache.log4j.Logger;//For JSP:<%@page import="org.apache.log4j.*"%>
You can get a logger object by calling the
Logger.getLogger()
method.
// Log4J does not make assumption to have a default appender. Later wewill use a different Log4j Configurator.BasicConfigurator.configure();Logger ul = Logger.getLogger(“a descriptive string”);Logger ul = Logger.getLogger(Myclass.class);
You may start logging by invoking one the logging methods, e.g.
info(), fatal(), warn(),
… Youmay set logging level as well. Level object has predefined constants, e.g. info, fatal, warn, etc.
//Set logging level, e.g. Level.All, Level.ERROR, Level.INFO.ul.setLevel(Level.INFO);//Start loggingul.info(“This is my logging output.”);ul.warn(“This is a warning.”);ul.debug(“This debug message will not appear”);
By using BasicConfigurator, the logger writes output to the console. However, you can specify adifferent appender, e.g. FileAppender. The following code shows you how to use the
PropertyConfigurator
class.
// You may use PropertyConfigurator to load a Log4J configuration file.// This tells the Log4J to watch the property file and reload when thefile has been modified.PropertyConfigurator.configureAndWatch(propertyfile);System.out.println("Loading the log4j property file: -> " +propertyfile);// After setting the Log4J configuraiton, you may use the logger.Logger ul = Logger.getLogger(Myclass.class);ul.inf(“logging to the output file specified by theconfiguration.
The Log4J configuration can use an external properties file. An example is shown below.
## Log for Java configuration don't change unless you know what you doing# The possible values here are debug, info, warn, error, fatal#log4j.rootCategory=info, R## Using Rolling File Appender#log4j.appender.R=org.apache.log4j.RollingFileAppender## This is the file that becomes the log file. Older log files are renamed asfileName.log.1 fileName.log.2 etc.#log4j.appender.R.File=C:\\MyDocuments\\g6_book\\java_src\\logging\\logs\\out.log## The maximum size of the log file, good idea to keep the size small.
3
Add a Comment