首先阅读log4j手册,配置滚动日志文件很容易。您不必执行任何显式的文件操作。
#SET LEVEL of ROOT-LOGGER, you will like to have Debug in local, but in prod you may just want WARN and ABOVE. This setting is done here!log4j.rootLogger=debug, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout# Pattern to output the caller's file name and line number. (basically, format of log)log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n# THIS IS WHERe YOU WILL HAVE ALL THE LOG WRITTENlog4j.appender.R=org.apache.log4j.RollingFileAppenderlog4j.appender.R.File=/var/log/applogs/example.log# Maximum size of log file, usually we keep 10MBlog4j.appender.R.MaxFileSize=100KB# Keep one backup file, usually we keep 10log4j.appender.R.MaxBackupIndex=1log4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
其次,每当您遇到异常时,都应这样做
public class MyClass{ private static Logger logger = Logger.getLogger(MyClass.class); public ReturnType myMethod(Param p, Param2 p2) { .... .... try { .. } catch(MyException e) { logger.log("Exceptions happen!", e); //this will put all the details in log file configured earlier } .... } ....}值得阅读手册。甚至最好阅读完整的log4j手册



