I am running a complex multithreaded Java application and facing some issue with logging exceptions.
There's a class ExceptionLogger which handles exception, here's the code snippet.
public class ExceptionLogger {
private enum EXTYPE {
ERROR, INFO, WARNING
}
private static Logger logger;;
private static void log(String message, EXTYPE msgtype) {
boolean append = true;
try {
FileHandler fh = new FileHandler("messages.log", append);
fh.setFormatter(new Formatter() {
@Override
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("messages");
logger.addHandler(fh);
switch (msgtype) {
case WARNING:
logger.warning(message);
break;
case ERROR:
logger.severe(message);
break;
case INFO:
logger.info(message);
break;
}
} catch (IOException e) {
e.printStackTrace();
}
public static synchronized void logEx(Exception e) {
// if(e.getMessage().compareTo("Widget is disposed")==0) return;
log("Error message :" + e.getMessage(), EXTYPE.ERROR);
e.printStackTrace();
log("cause :" + e.getCause(), EXTYPE.INFO);
}
}
Now the issue is that when multiple thread log exceptions multiple files are created like messages.log.1 messages.log.2 ...
Even though I have declared it as synchronized function, shouldn't the threads wait to log their exception, instead of creating new files.
Also 1 more thing with the e.getMessage() just gets me message like null pointer exception... No reference to class or line no. is there. How to get that as well. The code is soon going into production and I cannot rely on e.printStacktrace for debugging.
java.util.loggingpackage, log4j, slf4j, etc. You won't have to concern yourself with threading issues.