不能通過簡(jiǎn)單的配置log4j配置文件來實(shí)現(xiàn),而需要在代碼中調(diào)用Log4j的類來實(shí)現(xiàn)。下面給出實(shí)現(xiàn)類: /** * @author QG * * 2010-7-22 上午10:27:50 LoggerRun.java */ public class LoggerRun { //設(shè)定兩個(gè)Log public static Logger infoLogger = Logger.getLogger("info.logger"); public static Logger errorLogger = Logger.getLogger("error.logger"); public static final String PROFILE = "log4j.properties"; //設(shè)定異常log輸出的路徑 private static final String PATH = Constants.PATH; static{ try{ URL configFileResource = (new File(LoggerRun.class.getResource("/").getPath()+PROFILE)).toURL(); PropertyConfigurator.configure(configFileResource); }catch(Exception e){ e.printStackTrace(); } } public LoggerRun(){ try { Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = PATH + "exception_" + sf.format(date).toString() + ".log"; FileAppender exceptionAppender = new FileAppender(new SimpleLayout(), fileName); errorLogger.addAppender(exceptionAppender); } catch (Exception e) { e.printStackTrace(); } } } 同時(shí)給出配置文件配置信息: log4j.category.info.logger=INFO, info,stdout log4j.category.error.logger=ERROR,error log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss.SSS} %-5p %m%nlog4j.appender.info=org.apache.log4j.RollingFileAppender log4j.appender.info.File=bin/log/info.log log4j.appender.info.MaxFileSize=100kb log4j.appender.info.MaxBackupIndex=4 log4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss.SSS} %-5p %m%nlog4j.appender.error=org.apache.log4j.RollingFileAppender log4j.appender.error.File=bin/log/error.log log4j.appender.error.MaxFileSize=100kb log4j.appender.error.MaxBackupIndex=4 log4j.appender.error.layout=org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss.SSS} %-5p %m%n
在給出測(cè)試類: public class TestLog { public static final Logger logger=Logger.getLogger(TestLog.class); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub for(int i=0;i<10;i++){ if(i<5){ LoggerRun.infoLogger.info("TEST The Logger DUBUG!!!!"); }else{ LoggerRun.errorLogger.error("TEST THe LOGGER ERROR!!!!!!"); } } } }
同一個(gè)類中的日志按類型輸出到了不同的日志文件中。希望對(duì)大家能有所幫助。 |
|