今天看了一下《tomcat與Java web開發技術詳解》的第十七章,簡單地了解了Log4J的基本用法。
1.log4j.jar包,把他放到classpath裡
2.配置文件,這裡列舉其中一種,*.propertIEs方式的,文件如下
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
#log.propertIEs
#Logger組件log4j.rootLogger=warn,consolelog4j.logger.first=error,consolelog4j.logger.first.second=info,console
#Appender組件#console,file,GUI component,remot socket server,NT event Logger,remote UNIX syslog daemonlog4j.appender.console=org.apache.log4j.ConsoleAppender
#Layout組件#HtmlLayout,PatternLayout,SimpleLayout,TTCCLayoutlog4j.appender.console.layout=org.apache.log4j.SimpleLayout
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
3.在Java代碼裡調用
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
/* * Created on 2005-3-21 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */package log;
import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;
/** * @author baiming * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */public class JustLog4j{ static Logger rootLogger = Logger.getRootLogger(); static Logger firstLogger = Logger.getLogger("first"); static Logger secondLogger = Logger.getLogger("first.second"); public static void main(String[] args) { System.out.println("start"); System.out.println("+++++++++++++++++"); PropertyConfigurator.configure("log.propertIEs"); //rootLogger rootLogger.debug("root debug"); rootLogger.info("root info"); rootLogger.warn("root warn"); rootLogger.error("root error"); rootLogger.fatal("root fatal"); System.out.println("+++++++++++++++++"); //firstLogger firstLogger.debug("firstLogger debug"); firstLogger.info("firstLogger info"); firstLogger.warn("firstLogger warn"); firstLogger.error("firstLogger error"); firstLogger.fatal("firstLogger fatal"); System.out.println("+++++++++++++++++"); //secondLogger secondLogger.debug("secondLogger debug"); secondLogger.info("secondLogger info"); secondLogger.warn("secondLogger warn"); secondLogger.error("secondLogger error"); secondLogger.fatal("secondLogger fatal"); System.out.println("+++++++++++++++++"); System.out.println("end"); }}4.輸出結果
start+++++++++++++++++WARN - root warnERROR - root errorFATAL - root fatal+++++++++++++++++ERROR - firstLogger errorERROR - firstLogger errorFATAL - firstLogger fatalFATAL - firstLogger fatal+++++++++++++++++INFO - secondLogger infoINFO - secondLogger infoINFO - secondLogger infoWARN - secondLogger warnWARN - secondLogger warnWARN - secondLogger warnERROR - secondLogger errorERROR - secondLogger errorERROR - secondLogger errorFATAL - secondLogger fatalFATAL - secondLogger fatalFATAL - secondLogger fatal+++++++++++++++++end