log4j将日志写入任意名字的文件中,支持动态写入

log4j配置:

log4j.logger.presentOperatorLog=DEBUG, stdout, ilog  #既输出到控制台,也写入文件
log4j.additivity.presentOperatorLog = false  #日志不输出到父日志中,既rootLogger中
log4j.appender.ilog=org.apache.log4j.FileAppender
log4j.appender.ilog.File=/temp/test.log
log4j.appender.ilog.layout=org.apache.log4j.PatternLayout
#log4j.appender.ilog.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.ilog.layout.ConversionPattern=%d{yyyy-mm-dd HH:mm:ss} | %m

程序中:

private static Logger log = Logger.getLogger("presentOperatorLog"); //这里的presentOperatorLog就是上面定义的log4j.logger.presentOperatorLog
		
		Appender appender = Logger.getLogger("presentOperatorLog").getAppender("ilog");
		if(appender instanceof FileAppender){
            FileAppender fappender = (FileAppender) appender;
            Date dt = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyymmddhhmmss");
            String nowDate = sf.format(dt);
            
            fappender.setFile("E:/" + nowDate + ".log");//新日志文件的文件名:"E:/" + nowDate + ".log"
            fappender.activateOptions();  //启用新的日志文件
		}		
		log.debug("you got it man");


你可能感兴趣的:(c,Date,log4j,String)