启用日志记录
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
该库可为 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
等示例脚本时,通常会输出到控制台的所有日志消息都可以重定向(或“管道传输”)到文件。这是操作系统 shell 的一项功能,而不是 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
(或者,在某些新式 shell(例如 Bash 4+)中):
python get_campaigns.py -c $CLIENT_ID &> all_logs.txt
日志记录拦截器
Python 客户端库使用 gRPC 拦截器来访问和记录请求与响应的详细信息。您可以通过创建具有自定义逻辑的 gRPC 拦截器来设置自己的自定义日志记录。如需了解详情和自定义日志记录拦截器的示例,请参阅日志记录指南。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-27。
[null,null,["最后更新时间 (UTC):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."]]