项目中用log4j记录日志到指定目录

笔记之用


记录日志首先要有log4j.properties,配置如下:

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{yyyy-MM-dd HH:mm:ss} %p [%t] (%F:%L) - %m%n
 
log4j.rootLogger=info, stdout,DR
 
log4j.logger.org.hibernate.test=info
log4j.logger.org.hibernate.tool.hbm2ddl=debug
log4j.logger.org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator=trace
 
 
log4j.appender.DR=org.apache.log4j.RollingFileAppender
log4j.appender.DR.File=D:/apache-tomcat-6.0.32/logs/pageloading.log
log4j.appender.DR.MaxFileSize=10MB
# Archive log files
log4j.appender.DR.MaxBackupIndex=100
log4j.appender.DR.DatePattern='.'yyyy-MM-dd
log4j.appender.DR.layout=org.apache.log4j.PatternLayout
log4j.appender.DR.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss} %p [%t] (%F:%L) - %m%n

上面的log4j.appender.DR.File=D:/apache-tomcat- 6.0 . 32 /logs/pageloading.log就是指定日志的路径


在Action中要记录日志的话,首先要有

private Logger logger = Logger.getLogger(UserAction.class);--传进来的是当前类的clas
记录的话用

this.logger.info("具体信息");
this.logger.error("具体信息");

但是如果程序在执行的时候报异常了,是记录不了异常的,所以要对异常进行处理,比如说

try {
            System.out.println(10/0);//执行到这里会报异常
        } catch (Exception e) {
            StringWriter sw=new StringWriter();   
            PrintWriter pw=new PrintWriter(sw);
            e.printStackTrace(pw);
            this.logger.error(sw.toString());
        }

这样就把异常的错误详细信息给记录到日志里了



异常日志记录工具类

import java.io.PrintWriter;
import java.io.StringWriter;
 
import org.apache.log4j.Logger;
 
public class LogUtil {
 
    private LogUtil() {
 
    }
     
    private static StringWriter sw=new StringWriter();
    private static PrintWriter pw=new PrintWriter(sw);
 
    public static void info(Class logClass, Exception e) {
        Logger logger = Logger.getLogger(logClass);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    }
     
    public static void error(Class logClass, Exception e) {
        Logger logger = Logger.getLogger(logClass);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    }
     
    public static void warn(Class logClass, Exception e) {
        Logger logger = Logger.getLogger(logClass);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    }
     
    public static void debug(Class logClass, Exception e) {
        Logger logger = Logger.getLogger(logClass);
        e.printStackTrace(pw);
        logger.error(sw.toString());
    }
}

如何使用呢

try {
            System.out.println(10/0);
        } catch (Exception e) {
            LogUtil.info(UserAction.class, e);
        }

这样记录日志就方便了....

你可能感兴趣的:(log4j)