

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在適用於 C\$1\$1 的 AWS SDK 中設定和使用記錄
<a name="logging"></a>

 適用於 C\$1\$1 的 AWS SDK 包含可設定的記錄，可產生 SDK 在執行期間所執行動作的記錄。若要啟用記錄，請將 `LogLevel`的 設定為應用程式`SDKOptions`的適當詳細資訊。

```
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
```

有七個詳細程度可供選擇。預設值為 `Off`，不會產生任何日誌。 `Trace`會產生最詳細的層級，並`Fatal`產生最少的訊息，僅報告嚴重錯誤條件。

在您的應用程式中啟用記錄後，軟體開發套件將遵循 的預設命名模式，在您的可執行檔目錄中產生日誌檔案`aws_sdk_<date>.log`。字首命名選項產生的日誌檔案每小時會輪換一次，以允許 封存或刪除日誌檔案。

開發套件的更新版本越來越依賴基礎的 AWS 通用執行期 (CRT) 程式庫。這些程式庫提供 SDKs之間的常見功能和基本操作。根據預設，來自 CRT 程式庫的所有日誌訊息都會重新導向至適用於 C\$1\$1 的 SDK。您為適用於 C\$1\$1 的 SDK 指定的日誌層級和記錄系統也適用於 CRT。

在先前的範例中，CRT 會將層級的訊息繼承`LogLevel::Info`並記錄`Info`至相同的檔案。

您可以將 CRT 程式庫的日誌記錄獨立控制，方法是將其輸出重新導向至個別的日誌檔案，或從 CRT 為訊息設定不同的日誌層級。通常，減少 CRT 程式庫的詳細程度，使其不會壓倒日誌會很有幫助。例如，*只有* CRT 輸出的日誌層級可以設定為 `Warn` ，如下所示：

```
options.loggingOptions.crt_logger_create_fn =
    [](){ return Aws::MakeShared<Aws::Utils::Logging::DefaultCRTLogSystem>("CRTLogSystem", Aws::Utils::Logging::LogLevel::Warn); };
```

您可以選擇使用 方法`InitializeAWSLogging`，控制詳細資訊層級和 的日誌輸出`DefaultLogSystem`。您可以設定日誌檔案名稱字首，或將輸出重新導向至串流，而非檔案。

```
Aws::Utils::Logging::InitializeAWSLogging(
    Aws::MakeShared<Aws::Utils::Logging::DefaultLogSystem>(
        "RunUnitTests", Aws::Utils::Logging::LogLevel::Trace, "aws_sdk_"));
```

或者，您也可以使用此方法提供自己的記錄實作`DefaultLogSystem`，而不是使用 。

```
InitializeAWSLogging(Aws::MakeShared<CustomLoggingSystem>());
```

如果您呼叫方法 `InitializeAWSLogging`，請在程式結束時呼叫 以釋放資源`ShutdownAWSLogging`。

```
Aws::Utils::Logging::ShutdownAWSLogging();
```

 **與 記錄的範例整合測試** 

```
#include <aws/external/gtest.h>

#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/logging/DefaultLogSystem.h>
#include <aws/core/utils/logging/AWSLogging.h>

#include <iostream>

int main(int argc, char** argv)
{
    Aws::Utils::Logging::InitializeAWSLogging(
        Aws::MakeShared<Aws::Utils::Logging::DefaultLogSystem>(
            "RunUnitTests", Aws::Utils::Logging::LogLevel::Trace, "aws_sdk_"));
    ::testing::InitGoogleTest(&argc, argv);
    int exitCode = RUN_ALL_TESTS();
    Aws::Utils::Logging::ShutdownAWSLogging();
    return exitCode;
}
```

 **自訂記錄`Aws::Utils::Logging::DefaultLogSystem`的 子類別範例** 

 下列程式碼示範如何將 `Aws::Utils::Logging::DefaultLogSystem` 類別子分類，這是 的一部分 適用於 C\$1\$1 的 AWS SDK。此範例會覆寫`ProcessFormattedStatement`虛擬函數以自訂記錄。

 `Aws::Utils::Logging::DefaultLogSystem` 是 中`Aws::Utils::Logging::LogSystemInterface`用於自訂記錄 適用於 C\$1\$1 的 AWS SDK 的子類別之一。

```
class LogSystemOverride : public Aws::Utils::Logging::DefaultLogSystem {
public:
    explicit LogSystemOverride(Aws::Utils::Logging::LogLevel logLevel,
                               const Aws::String &logPrefix)
            : DefaultLogSystem(logLevel, logPrefix), mLogToStreamBuf(false) {}

    const Aws::Utils::Stream::SimpleStreamBuf &GetStreamBuf() const {
        return mStreamBuf;
    }

    void setLogToStreamBuf(bool logToStreamBuf) {
        mLogToStreamBuf = logToStreamBuf;
    }

protected:

    void ProcessFormattedStatement(Aws::String &&statement) override {
        if (mLogToStreamBuf) {
            std::lock_guard<std::mutex> lock(mStreamMutex);
            mStreamBuf.sputn(statement.c_str(), statement.length());
        }

        DefaultLogSystem::ProcessFormattedStatement(std::move(statement));
    }

private:
    Aws::Utils::Stream::SimpleStreamBuf mStreamBuf;
    // Use a mutex when writing to the buffer because
    // ProcessFormattedStatement can be called from multiple threads.
    std::mutex mStreamMutex;
    std::atomic<bool> mLogToStreamBuf;
};
```

```
int main(int argc, char **argv) {
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    auto logSystemOverride = Aws::MakeShared<LogSystemOverride>("AllocationTag",
                                                                options.loggingOptions.logLevel,
                                                                options.loggingOptions.defaultLogPrefix);
    options.loggingOptions.logger_create_fn = [logSystemOverride]() {
        return logSystemOverride;
    };

    Aws::InitAPI(options);  // Call Aws::InitAPI only once in an application.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::S3::S3Client s3Client(clientConfig);

        logSystemOverride->setLogToStreamBuf(true);
        auto outcome = s3Client.ListBuckets();
        if (!outcome.IsSuccess()) {
            std::cerr << "ListBuckets error: " <<
                      outcome.GetError().GetExceptionName() << " " <<
                      outcome.GetError().GetMessage() << std::endl;
        }

        logSystemOverride->setLogToStreamBuf(false);

        std::cout << "Log for ListBuckets" << std::endl;
        std::cout << logSystemOverride->GetStreamBuf().str() << std::endl;
    }

    Aws::ShutdownAPI(options);

    return 0;
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sdk-customization/override_default_logger.cpp)。