正确使用 log4j 和异常

Correct use of log4j and Exceptions

我对带异常的 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);

提前致谢。

例外只是signals/events;发生在您的应用程序范围内。记录这些是另一个主题。

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

最简单的情况可能是:

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 中登录,还是只想给调用者一个信号,表明发生了异常?或者两者兼而有之(就像上面的例子一样?)。

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