gpt4 book ai didi

java - 正确使用log4j和异常

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

我对 log4j 与异常的使用有疑问。我想将消息记录到我的日志文件中,但我不知道如何处理异常。我必须仅使用异常(因为已经在我的日志文件中打印)或以下内容:

try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();

} catch (Exception e) {
log.error(new AmazonClientException("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e));

或者这个

try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();

} catch (Exception e) {
log.error("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e);
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",
e);

提前致谢。

最佳答案

异常只是信号/事件;在您的应用程序范围内发生的情况。记录这些是另一个主题。

我了解您需要在应用程序中记录有用的消息。在您的情况下,您可以在您的方法的使用者上触发日志事件,或者直接按照您的操作触发日志事件。

最简单的情况可能是:

try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
AmazonClientException ace = AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.", e);

log.error(ace.getMessage(), ace);
throw ace;
}

try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
log.error("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e);
throw new AmazonClientException(e);
}

上面的例子只是一个实现,并不是对你原来问题的答案。要回答最初的问题,您必须清楚地了解您的 API 以及 API 设计中产生的职责。您想要登录 API 还是只想向调用者发出发生异常的信号?或者两者兼而有之(就像上面的例子一样?)。

在使用异常或任何其他方式传播意外状态之前,请回答以下问题:应如何处理这种情况?异常后应该发生什么?日志记录也不异常(exception);这只是记录。找到答案后,您可以寻找适当的方式来传达意外状态。

关于java - 正确使用log4j和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30568673/

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