如何用Java记录纯文本? SimpleFormatter也编写XML

时间:2016-06-08 23:14:43

标签: java logging

我正在使用SimpleFormatter编写日志文件。这些是用XML而不是纯文本编写的。我发现将它写为纯文本的答案都只是说使用简单的格式化程序(例如https://stackoverflow.com/a/10469185/651779)。这是我的自定义记录格式化程序,它从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();
    }
} 

这就是我设置记录器的方法

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);

  }
}

我错过了什么,它不写入纯文本?

1 个答案:

答案 0 :(得分:2)

outfilePath的格式化程序是s XMLFormatter 您应该致电outfilePath.setFormatter(customFormatter);进行更改。