

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS SDK for C\$1\$1에서 로깅 구성 및 사용
<a name="logging"></a>

AWS SDK for C\$1\$1에는 실행 중에 SDK가 수행한 작업의 레코드를 생성하는 구성 가능한 로깅이 포함되어 있습니다. 로깅을 활성화하려면 `SDKOptions`의 `LogLevel`을 애플리케이션에 적합한 상세 수준으로 설정합니다.

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

선택할 수 있는 상세 수준은 7가지입니다. 기본값은 `Off`이며 이 경우 로그가 생성되지 않습니다. `Trace`는 가장 상세한 정보를 생성하며, `Fatal`은 치명적인 오류 상태만 보고하는 최소한의 메시지만 생성합니다.

애플리케이션에서 로깅이 활성화되면 SDK는 `aws_sdk_<date>.log`의 기본 이름 지정 패턴에 따라 실행 파일 디렉터리에 로그 파일을 생성합니다. 접두사 이름 지정 옵션으로 생성된 로그 파일은 로그 파일 보관 또는 삭제를 위해 매시간마다 롤오버됩니다.

SDK의 최신 버전은 기본 AWS 공통 런타임(CRT) 라이브러리에 점점 더 의존하고 있습니다. 이러한 라이브러리는 SDK 간 공통 기능과 기본 작업을 제공합니다. CRT 라이브러리에서 발생하는 모든 로그 메시지는 기본적으로 SDK for C\$1\$1로 리디렉션됩니다. SDK for C\$1\$1에 대해 지정하는 로그 수준 및 로깅 시스템이 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 SDK for C\$1\$1의 일부인 `Aws::Utils::Logging::DefaultLogSystem` 클래스를 하위 클래스로 분류하는 방법을 보여줍니다. 이 예제에서는 `ProcessFormattedStatement` 가상 함수를 재정의하여 로깅을 사용자 지정합니다.

 `Aws::Utils::Logging::DefaultLogSystem`은 AWS SDK for C\$1\$1의 여러 클래스 중 하나로, 사용자 지정 로깅을 위해 `Aws::Utils::Logging::LogSystemInterface`을 하위 클래스로 분류합니다.

```
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;
}
```

[전체 예제](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sdk-customization/override_default_logger.cpp)는 GitHub에서 확인하세요.