log4j记录运行日志
1、在工程中导入log4j-1.2.15.jar的jar包
2、新建测试类
package control; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * @author janeky * Log演示程序 */ public class Log { //Logger实例 public Logger loger; //将Log类封装成单实例的模式,独立于其他类。以后要用到日志的地方只要获得Log的实例就可以方便使用 private static Log log; //构造函数,用于初始化Logger配置需要的属性 private Log(String dir) { loger=Logger.getLogger(this.getClass()); } public static Log getLoger(String dir) { if(log!=null) return log; else return new Log(dir); } //测试函数 public static void main(String args[]) { Log log=Log.getLoger(); try { //引发异常 int a=2/0; }catch(Exception e) { //控制台打印异常信息 e.printStackTrace(); //写入到日子文件 log.loger.error("error", e); // log.loger.debug("Log4jTest-->>debug"); // log.loger.info("Log4jTest-->>info"); // log.loger.warn("Log4jTest-->>warn"); // log.loger.error("Log4jTest-->>error"); } } }
3、新建配置文件:log4j.properties (在工程下新建log文件夹,在log文件夹下建log4j.properties),粘贴以下内容到log4j.properties
log4j.rootLogger=DEBUG, A1, A2 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %d{yyyy-MM-dd HH:mm:ss} %c %m%n log4j.appender.A2=org.apache.log4j.RollingFileAppender log4j.appender.A2.File=Log4jTest.log log4j.appender.A2.MaxFileSize=20KB log4j.appender.A2.MaxBackupIndex=1 log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%-4r %-5p %d{yyyy-MM-dd HH:mm:ss} %c %m%n
或者
log4j.rootLogger = debug,stdout,E log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.appender.E= org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =${catalina.home}/logs/StaffService.log log4j.appender.E.DatePattern='.'yyyy-MM-dd log4j.appender.E.ImmediateFlush=true log4j.appender.E.Threshold =DEBUG log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p] %m%n
注意:catalina.home是指tomcat的安装路径