啟用 Logging
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
這個程式庫提供多種記錄 Google Ads API 互動的方式。你可以擷取:
- 詳細資訊:傳送至 API 的完整要求和收到的回應。
- 簡明摘要:互動的概要總覽。
您可以透過兩種方式控管這些記錄設定:
- 用戶端程式庫設定:使用程式庫的特定設定選項。
- 透過 Python 以程式輔助方式操作:使用 Python 的內建 logging 架構,直接控管記錄。
初始化 GoogleAdsClient
執行個體時,系統會自動設定記錄功能。舉例來說,當您使用 load_from_storage
方法時,就會發生這個初始化步驟。此時,程式庫會:
當這個程式庫做為已安裝的套件使用時,您需要將其記錄與應用程式的記錄設定整合。具體來說,您必須使用 addHandler
方法,將記錄處理常式新增至程式庫本身的記錄器例項。這個處理常式會決定程式庫的記錄訊息要導向何處 (例如控制台、檔案等)。如要這麼做,請先擷取程式庫的記錄器例項,如下所示:
import logging
logger = logging.getLogger('google.ads.googleads.client')
擷取程式庫的記錄器後,您可以指定記錄訊息的輸出位置。
將記錄檔傳送至控制台:如要在控制台上顯示記錄訊息,請新增基本處理常式。以下說明如何將記錄導向標準輸出 (stdout
):
以下說明如何設定基本處理常式,讓記錄器將內容列印至 stdout
:
import sys
# Assuming 'logger' was retrieved as per previous instructions
logger.addHandler(logging.StreamHandler(sys.stdout))
如要將記錄傳送至標準錯誤 (stderr
),這通常用於錯誤訊息和警告:
import sys
# Assuming 'logger' was retrieved as per previous instructions
logger.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 程式庫本身。步驟如下:
如要將標準輸出內容 (大部分的記錄) 儲存至檔案 (並覆寫檔案),請執行下列操作:
python get_campaigns.py -c $CLIENT_ID > campaign_logs.txt
如要將標準輸出內容附加至檔案:
python get_campaigns.py -c $CLIENT_ID >> campaign_logs.txt
如要將標準輸出和標準錯誤 (適用於錯誤/警告) 儲存至同一個檔案,請按照下列步驟操作:
python get_campaigns.py -c $CLIENT_ID > all_logs.txt 2>&1
(或者,在 Bash 4 以上版本等部分新式殼層中):
python get_campaigns.py -c $CLIENT_ID &> all_logs.txt
記錄攔截器
Python 用戶端程式庫會使用 gRPC 攔截器存取及記錄要求和回應詳細資料。您可以建立具有自訂邏輯的 gRPC 攔截器,設定自己的自訂記錄。如需更多詳細資料和自訂記錄攔截器的範例,請參閱「記錄」指南。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-27 (世界標準時間)。
[null,null,["上次更新時間:2025-08-27 (世界標準時間)。"],[[["\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."]]