Primera leer log4j Manual, es fácil para configurar un archivo de registro continuo No tiene que hacer ninguna operación de archivo explícita.
#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
En segundo lugar, cada vez que se captura una excepción, hacer como esto
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
}
....
}
....
}
Vale la pena leer el manual. Mejor aún, lea Complete log4j Manual
y ¿qué hago cuando aparecen excepciones sin marcar? ¿Cómo puedo estar seguro de que TODO se enviará al registrador? – Blauhirn
Usa 'Throwable' para atrapar * todo *. No es aconsejable. Es posible que desee leer estas publicaciones: 1. http://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation 2. http://stackoverflow.com/questions/2274102/difference-between -usando-throwable-and-exception-in-a-try-catch – Nishant
@Nishant ¿Dónde se ubicará el archivo de registro? ¿Está dentro de la carpeta apache? – KJEjava48