Niek de Klein Niek de Klein - 6 months ago 8
Java Question

How to log plain text in Java? SimpleFormatter also writes XML

I am writing logfiles using SimpleFormatter. These are written in XML instead of plain text. The answers I found for writing it as plain text all only say to use the simple formatter (e.g. http://stackoverflow.com/a/10469185/651779). This is my custom record formatter, which extends from SimpleFormatter:

class CustomRecordFormatter extends SimpleFormatter {
@Override
public String format(final LogRecord r) {
StringBuilder sb = new StringBuilder();
sb.append(formatMessage(r)).append(System.getProperty("line.separator"));
if (null != r.getThrown()) {
sb.append("Throwable occurred: "); //$NON-NLS-1$
Throwable t = r.getThrown();
PrintWriter pw = null;
try {
StringWriter sw = new StringWriter();
pw = new PrintWriter(sw);
t.printStackTrace(pw);
sb.append(sw.toString());
} finally {
if (pw != null) {
try {
pw.close();
} catch (Exception e) {
// ignore
}
}
}
}
return sb.toString();
}
}


and this is how I set up the logger

public class DeconvolutionLogger {
static private FileHandler outfilePath;
protected final static Logger log = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
static public void setup(String outputDir) throws IOException {
// get the global logger to configure it
log.setLevel(Level.INFO);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
setOutfilePath(new FileHandler(outputDir+"/DeconvolutionLog_"+dateFormat.format(date)+".txt"));
CustomRecordFormatter customFormatter = new CustomRecordFormatter();
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(customFormatter);
log.setUseParentHandlers(false);
log.addHandler(consoleHandler);
log.addHandler(outfilePath);

}
}


What am I missing that it does not write to plain text?

Answer

The formatter of outfilePath is stil XMLFormatter.
You should call outfilePath.setFormatter(customFormatter); to change it.