gpt4 book ai didi

java - 如何在Java中记录纯文本? SimpleFormatter 还可以写入 XML

转载 作者:行者123 更新时间:2023-12-02 03:33:42 25 4
gpt4 key购买 nike

我正在使用 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);

}
}

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

最佳答案

outfilePath 的格式化程序仍然是 XMLFormatter
您应该调用 outfilePath.setFormatter(customFormatter); 来更改它。

关于java - 如何在Java中记录纯文本? SimpleFormatter 还可以写入 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37714454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com