[英]How to solve the exception logging problem which I have in Java?
我使用了记录器 object 并添加文件处理程序以在 Java 项目的日志文件中记录异常。 它工作正常,当我从 NetBeans IDE 运行它时,但是当我从控制台将它作为独立应用程序运行时,异常记录在控制台中,甚至没有在我指定的位置创建文件。
private static final Logger LOGGER = Logger.getLogger(BuyerRegistration.class.getName());
public static void main(String args[]) {
Formatter simpleFormatter = null;
Handler fileHandler = null;
try {
LOGGER.setUseParentHandlers(false);
fileHandler = new FileHandler("dist/lib/CurryHouse.log", true);
simpleFormatter = new SimpleFormatter();
LOGGER.addHandler(fileHandler);
fileHandler.setFormatter(simpleFormatter);
fileHandler.setLevel(Level.ALL);
LOGGER.setLevel(Level.ALL);
} catch (IOException exception) {
LOGGER.log(Level.SEVERE, "Error occur in FileHandler.", exception);
}
上面的代码将出现在 BuyerRegistration class 中。 此外,我在所有 catch 块中附加了以下代码,以在文件中记录异常。
LOGGER.log(Level.SEVERE, "{0}\n", "Bills:352\t" + e.toString());
我希望代码在我指定的位置记录所有异常,而不是登录控制台
我从控制台将它作为独立应用程序运行,异常记录在控制台中,甚至没有在我指定的位置创建文件。
您正在使用当前目录更改时更改的相对路径。 使用绝对路径、 FileHandler 模式或在启动器中设置当前目录。
我希望代码在我指定的位置记录所有异常,而不是登录控制台
将您的处理程序添加到根记录器而不是您的命名记录器。 您可以通过提供logging.properties 或配置 class来做到这一点。
private static final Logger ROOT = Logger.getLogger("");
static {
Formatter simpleFormatter = null;
Handler fileHandler = null;
try {
//TODO: Fix file path
fileHandler = new FileHandler("%h/CurryHouse.log", true);
simpleFormatter = new SimpleFormatter();
LOGGER.addHandler(fileHandler);
fileHandler.setFormatter(simpleFormatter);
fileHandler.setLevel(Level.ALL);
ROOT.addHandler(fileHandler);
} catch (IOException exception) {
LOGGER.log(Level.SEVERE, "Error occur in FileHandler.", exception);
}
}
public static void main(String args[]) {
//Your app.
}
此外,我在所有 catch 块中附加了以下代码,以在文件中记录异常。
您可能需要考虑记录完整的堆栈跟踪:
LOGGER.log(Level.SEVERE, "Bills:352", e);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.