gpt4 book ai didi

java - 如何从 java.util.logging.Logger Logging 记录消息,然后将其打印到文本文件?

转载 作者:行者123 更新时间:2023-12-01 13:42:11 25 4
gpt4 key购买 nike

“logger.info(消息);”我的代码中的行创建此输出:

Dec 17, 2013 12:54:50 PM greenhouse.GreenhouseControls$ControllerException

我想使用 PrintWriter 将该行打印到文本文件中。这是我到目前为止所拥有的:

public ControllerException(String message, int errorcode) {
super(message);
this.errorcode=errorcode;

Logger logger = Logger.getLogger(ControllerException.class.getName());
logger.info(message);

String fileName = "error.log";

try {
PrintWriter outputStream = new PrintWriter(fileName);
outputStream.println("Time: " + ????); // Not sure what to put here..
outputStream.println("Reason: " + message);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

我可以在打印行语句中包含什么来代替问号来实现此目的?

最佳答案

我会这样做:

public ControllerException(final String message, int errorcode) {
super(message);
this.errorcode=errorcode;

Logger logger = Logger.getLogger(ControllerException.class.getName());

logger.setFilter(new Filter() {
@Override
public boolean isLoggable(LogRecord record) {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd',' yyyy HH:mm:ss a");
String fileName = "error.log";

try {
PrintWriter outputStream = new PrintWriter(fileName);
outputStream.println("Time: " + sdf.format(new Date(record.getMillis())));
outputStream.println("Reason: " + message);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

return true;
}
});

logger.info(message);
}

这样您就可以获得日志记录的确切日期。

关于java - 如何从 java.util.logging.Logger Logging 记录消息,然后将其打印到文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20644619/

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