이 라이브러리를 설치된 패키지로 사용하는 경우 로깅을 애플리케이션의 로깅 설정과 통합해야 합니다. 특히 addHandler 메서드를 사용하여 라이브러리의 자체 로거 인스턴스에 로깅 핸들러를 추가해야 합니다. 이 핸들러는 라이브러리의 로그 메시지가 전송되는 위치(예: 콘솔, 파일 등)를 지정합니다. 이렇게 하려면 먼저 다음과 같이 라이브러리의 로거 인스턴스를 가져옵니다.
콘솔에 로그 전송: 콘솔에 로그 메시지를 표시하려면 기본 핸들러를 추가합니다. 로그를 표준 출력 (stdout)으로 전달하는 방법은 다음과 같습니다.
다음은 로거가 stdout에 출력하도록 지시하는 기본 핸들러를 설정하는 방법입니다.
importsys# Assuming 'logger' was retrieved as per previous instructionslogger.addHandler(logging.StreamHandler(sys.stdout))
오류 메시지 및 경고에 자주 사용되는 표준 오류 (stderr)에 로그를 전송하려면 다음 단계를 따르세요.
importsys# Assuming 'logger' was retrieved as per previous instructionslogger.addHandler(logging.StreamHandler(sys.stderr))
프로그래매틱 방식으로 기타 로깅 설정 구성: 로거 객체가 있으면 Python의 내장 logging 모듈을 사용하여 프로그래매틱 방식으로 기타 로깅 설정을 변경할 수도 있습니다. 예를 들어 로깅 수준을 DEBUG로 변경하여 더 자세한 메시지를 표시하려면 다음을 실행합니다.
logger.setLevel(logging.DEBUG)
로그 수준
클라이언트는 몇 가지 다른 수준에서 로그를 생성하며 아래의 일부 또는 전부를 볼 수 있도록 구성을 설정할 수 있습니다.
수준
성공한 요청
실패한 요청
DEBUG
전체 요청 및 응답 객체가 JSON으로 포함된 자세한 로그입니다.
전체 요청 및 예외 객체가 JSON으로 포함된 세부 로그입니다.
INFO
구체적인 요청 및 응답 필드가 포함된 간결한 요약
전체 요청 및 예외 객체가 JSON으로 포함된 세부 로그입니다.
WARNING
없음
구체적인 요청 정보, 예외 상태, 메시지가 포함된 간결한 요약입니다.
Python 로깅 프레임워크는 구성된 수준보다 심각도가 낮은 로그 메시지를 무시하므로 WARNING로 설정하면 실패한 요청과 관련된 간결한 메시지만 표시되지만 DEBUG로 설정하면 위의 표에 있는 모든 유형의 로그가 표시됩니다.
파일에 로깅
명령줄에서 get_campaigns.py과 같은 예시 스크립트를 실행하면 일반적으로 콘솔에 출력되는 로그 메시지를 파일로 리디렉션('파이프')할 수 있습니다. 이는 Python 라이브러리 자체가 아닌 운영체제 셸의 기능입니다. 방법은 다음과 같습니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[[["\u003cp\u003eThe Google Ads API Python client library offers configurable logging for interactions, allowing detailed or summary logs of requests and responses.\u003c/p\u003e\n"],["\u003cp\u003eLogging is managed via the client library configuration and utilizes Python's built-in logging framework, outputting to \u003ccode\u003estderr\u003c/code\u003e by default.\u003c/p\u003e\n"],["\u003cp\u003eLog levels can be adjusted (\u003ccode\u003eDEBUG\u003c/code\u003e, \u003ccode\u003eINFO\u003c/code\u003e, \u003ccode\u003eWARNING\u003c/code\u003e) to control the verbosity and types of logged information, impacting visibility into successful and failed requests.\u003c/p\u003e\n"],["\u003cp\u003eLogs can be directed to a file for persistent storage, and custom logging interceptors can be implemented for tailored logging behavior beyond the library's built-in options.\u003c/p\u003e\n"]]],[],null,["# Enable Logging\n\nThe library provides versatile logging for Google Ads API interactions. You can\ncapture:\n\n- Detailed information: Full requests sent to the API and responses received.\n- Concise summaries: A high-level overview of the interactions.\n\nAnd you can control these logging settings in two ways:\n\n- Client Library Configuration: Use the library's specific [configuration](/google-ads/api/docs/client-libs/python/configuration) options.\n- Programmatically with Python: Use Python's built-in [logging](//docs.python.org/3.7/library/logging.html) framework for more direct control.\n\nLogging is configured automatically when a `GoogleAdsClient` instance is\ninitialized. This initialization step occurs, for example, when you use the\n`load_from_storage` method. At this point, the library will:\n\n- Read your specified logging settings from its [configuration](/google-ads/api/docs/client-libs/python/configuration).\n- Pass these settings to Python's built-in [`logging.config.dictConfig`](//docs.python.org/3.7/library/logging.config.html#logging.config.dictConfig) to activate them.\n\nWhen this library is used as an installed package, you need to integrate its\nlogging with your application's logging setup. Specifically, you must add a\nlogging handler to the library's own logger instance with the\n[`addHandler`](//docs.python.org/3/library/logging.html#logging.Logger.addHandler)\nmethod. This handler will dictate where the library's log messages are directed\n(e.g., to the console, a file, etc.). To do this, first retrieve the library's\nlogger instance as shown here: \n\n import logging\n\n logger = logging.getLogger('google.ads.googleads.client')\n\nAfter retrieving the library's logger, you can tell it where to output log\nmessages.\n\n- Sending Logs to the Console: To display log messages on your console, you\n add a basic handler. Here's how to direct logs to standard output (`stdout`):\n\n And here's how to set a basic handler that will tell the logger to print to\n `stdout`: \n\n import sys\n\n # Assuming 'logger' was retrieved as per previous instructions\n logger.addHandler(logging.StreamHandler(sys.stdout))\n\n If you prefer to send logs to standard error (`stderr`), which is often used\n for error messages and warnings: \n\n import sys\n\n # Assuming 'logger' was retrieved as per previous instructions\n logger.addHandler(logging.StreamHandler(sys.stderr))\n\n- Configuring Other Logging Settings Programmatically: Once you have the\n logger object, you can also programmatically change other logging settings\n using Python's built-in [logging](//docs.python.org/3.7/library/logging.html)\n module. For example, to change the logging level to `DEBUG` (which will show\n more detailed messages):\n\n logger.setLevel(logging.DEBUG)\n\nLog levels\n----------\n\nThe client generates logs at a few different levels and you can set your\nconfiguration to see some or all of the below:\n\n| Level | Successful Request | Failed Request |\n|-----------|--------------------------------------------------------------------|---------------------------------------------------------------------------------------|\n| `DEBUG` | A detailed log with complete request and response objects as JSON. | A detailed log with complete request and exception objects as JSON. |\n| `INFO` | A concise summary with specific request and response fields. | A detailed log with complete request and exception objects as JSON. |\n| `WARNING` | None | A concise summary with specific request information, the exception state and message. |\n\nSince the Python logging framework ignores log messages that are less severe\nthan the configured level, setting to `WARNING` means you will only see\nconcise messages related to failed requests, but setting to `DEBUG` means\nyou will see all possible types of logs in the above table.\n\nLogging to file\n---------------\n\nWhen you run example scripts like\n[`get_campaigns.py`](//github.com/googleads/google-ads-python/blob/main/examples/basic_operations/get_campaigns.py)\nfrom your command line, any log messages typically printed to the console can\nbe redirected (or \"piped\") to a file. This is a feature of your operating\nsystem's shell, not the Python library itself. Here's how:\n\nTo save standard output (most logs) to a file (overwriting it): \n\n python get_campaigns.py -c $CLIENT_ID \u003e campaign_logs.txt\n\nTo append standard output to a file: \n\n python get_campaigns.py -c $CLIENT_ID \u003e\u003e campaign_logs.txt\n\nTo save both standard output and standard error (for errors/warnings) to the\nsame file: \n\n python get_campaigns.py -c $CLIENT_ID \u003e all_logs.txt 2\u003e&1\n\n(Or, on some modern shells like Bash 4+): \n\n python get_campaigns.py -c $CLIENT_ID &\u003e all_logs.txt\n\nLogging interceptors\n--------------------\n\nThe Python client library uses gRPC\n[interceptors](//grpc.io/blog/grpc-web-interceptor) to access and log request\nand response details. You can set up your own custom logging by creating a gRPC\ninterceptor with custom logic. See the [Logging\nguide](/google-ads/api/docs/best-practices/logging#option_4_implement_a_custom_grpc_logging_interceptor)\nfor more details and an example of a custom logging interceptor."]]