首先閱讀log4j Manual,很容易配置滾動日誌文件。你不必做任何明確的文件操作。
#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, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.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 WRITTEN
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/var/log/applogs/example.log
# Maximum size of log file, usually we keep 10MB
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file, usually we keep 10
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.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
}
....
}
....
}
它值得閱讀的手冊。更好的閱讀Complete log4j Manual
以及當未經檢查的例外出現時我該怎麼辦?我怎樣才能確保一切將被髮送到記錄器? – Blauhirn 2015-02-17 20:16:17
使用'Throwable'來捕捉*一切*。但不可取。你可能想閱讀這些帖子:1. http://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation 2. http://stackoverflow.com/questions/2274102/difference-between -using-throwable-and-try-catch – Nishant 2015-02-18 06:57:33
@Nishant日誌文件位於何處?它在apache文件夾內嗎? – KJEjava48 2017-04-03 11:27:14