.NET 客户端库会记录向 Google Ads API 发出的请求、响应和摘要消息。日志可以写入自定义 TraceListener 或自定义 ILogger 实例。
TraceListener
您可以在 Main 方法中添加以下代码行,以启用向 TraceListener 的日志记录功能,然后再进行任何 API 调用:
using Google.Ads.GoogleAds.Util;
// Detailed logs.
TraceUtilities.Configure(
TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE,
"logs/details.log",
System.Diagnostics.SourceLevels.All);
// Summary logs.
TraceUtilities.Configure(
TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE,
"logs/summary.log",
System.Diagnostics.SourceLevels.All);
ILogger
如果您已在应用日志中使用 ILogger,则此解决方案可让您将 Google Ads API 日志集成到现有的日志记录基础架构中。
首先,创建一个 LoggerFactory,或者如果您已有
,请添加 Google Ads API 日志的过滤条件:
var loggerFactory = LoggerFactory.Create(builder =>
{
// Log to stdout.
builder.AddConsole();
builder.AddFilter(
TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE, LogLevel.Trace);
builder.AddFilter(
TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE, LogLevel.Trace);
});
然后,使用 LoggerFactory 为请求和响应摘要及详细信息创建记录器:
ILogger summaryLogger = loggerFactory.CreateLogger(
TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE);
ILogger detailLogger = loggerFactory.CreateLogger(
TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE);
最后,配置客户端库以将其轨迹重定向到您的 ILogger 实例:
TraceUtilities.ConfigureSummaryLogger(summaryLogger);
TraceUtilities.ConfigureDetailLogger(detailLogger);
此解决方案可让您将 Google Ads API 请求和响应日志集成到现有的日志记录框架中,例如 Log4Net、NLog 和 Serilog。
日志级别
该库会在不同的日志级别记录不同类型的事件:
- 成功的 API 响应:摘要记录在
INFO;完整请求和响应记录在DEBUG。 - API 错误响应:摘要消息记录在
WARN;完整请求和响应记录在INFO。 - 部分失败:记录在
DEBUG中。
请求 ID
在大多数情况下,客户端库生成的日志会提供足够的详细信息来帮助您排查问题。当您与支持团队联系时,请提供日志(默认情况下,日志会编辑敏感的身份验证字段),或分享请求 ID(该 ID 会记录为响应日志的一部分)。
如果您希望以编程方式捕获请求 ID,请使用以下方法之一。
从普通的一元 API 调用中提取
您可以将自定义 CallSettings 与 TrailingMetadataHandler 搭配使用,以捕获常规一元调用的请求 ID:
CallSettings callSettings = CallSettings.FromTrailingMetadataHandler(
metadata =>
{
// Extract and log the request ID from the trailing metadata.
string requestId = metadata.Get("request-id")?.Value;
Console.WriteLine($"Request ID: {requestId}");
});
// Add the campaigns.
MutateCampaignsResponse retVal = campaignService.MutateCampaigns(
customerId.ToString(), operations.ToArray(), callSettings);
从流式传输 API 调用中提取
请求 ID 作为流式 API 调用的响应对象的一部分返回。例如,您可以按如下方式获取 SearchStream 调用的请求 ID:
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V25.GoogleAdsService);
// Retrieve all campaigns.
string query = @"SELECT
campaign.id,
campaign.name,
campaign.network_settings.target_content_network
FROM campaign
ORDER BY campaign.id";
// Issue a search request.
googleAdsService.SearchStream(
customerId.ToString(),
query,
(SearchGoogleAdsStreamResponse resp) =>
{
// Extract the request ID from the response.
string requestId = resp.RequestId;
Console.WriteLine($"Request ID: {requestId}");
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
Console.WriteLine(
"Campaign with ID {0} and name '{1}' was found.",
googleAdsRow.Campaign.Id,
googleAdsRow.Campaign.Name);
}
}
);
例外情况
每当 API 调用失败时,系统都会在 GoogleAdsException 异常中返回请求 ID:
try
{
// Make an API call.
}
catch (GoogleAdsException e)
{
string requestId = e.RequestId;
Console.WriteLine($"Failed Request ID: {requestId}");
}
配置高级日志记录
如果 API 日志未提供足够的详细信息,请在 gRPC 传输级别启用更低级别的日志记录。请注意,输出内容可能非常多。
使用默认 Grpc.Net.Client 传输时,通过 .NET 的 ILogger 提供程序添加 Grpc 类别的过滤条件(例如 builder.AddFilter("Grpc", LogLevel.Debug)),来配置传输级日志。
如果您使用的是旧版 Grpc.Core 传输 (UseGrpcCore = true),gRPC 日志默认会写入 stderr,您也可以附加自己的记录器,如以下示例所示。如需了解详情,请参阅支持的 gRPC 环境变量。
Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
Environment.SetEnvironmentVariable("GRPC_TRACE", "http");
GrpcEnvironment.SetLogger(new ConsoleLogger());
使用 App.config(旧版)的 TraceListener 配置
如果您的应用是针对 .NET Framework 目标构建的,则可以从应用的 App.config 或 Web.config 文件中加载日志记录配置。这是一项旧版 .NET 功能,不支持为新版 .NET 目标平台构建的应用。
如需使用此功能,请向配置文件添加以下更改:
在
<configuration>部分下添加以下代码段:<system.diagnostics> <sources> <source name="GoogleAds.DeprecationMessages" switchName="GoogleAds.DeprecationMessages" switchType="System.Diagnostics.SourceSwitch"> <listeners> <add name="myListener" type="System.Diagnostics.EventLogTraceListener" initializeData="Application" /> </listeners> </source> <source name="GoogleAds.DetailedRequestLogs" switchName="GoogleAds.DetailedRequestLogs" switchType="System.Diagnostics.SourceSwitch"> <listeners> <add name="detailedRequestLogListener" type="System.Diagnostics.ConsoleTraceListener" initializeData="true" /> <!-- Use the following to log to a file. Modify the initializeData attribute to control the path to the detailed request log file. --> <!-- <add name="detailedRequestLogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Logs\detailed_logs.log" /> <remove name="Default" /> --> </listeners> </source> <source name="GoogleAds.SummaryRequestLogs" switchName="GoogleAds.SummaryRequestLogs" switchType="System.Diagnostics.SourceSwitch"> <listeners> <add name="summaryRequestLogListener" type="System.Diagnostics.ConsoleTraceListener" initializeData="true" /> <!-- Use the following to log to a file. Modify the initializeData attribute to control the path to the summary request log file. --> <!-- <add name="summaryRequestLogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Logs\summary_logs.log" /> --> <remove name="Default" /> </listeners> </source> </sources> <switches> <!-- Use this trace switch to control the deprecation trace messages written by Google Ads .NET libraries. The default level is set to Warning. To disable all messages, set this value to Off. --> <add name="GoogleAds.DeprecationMessages" value="Warning" /> <!-- Use this trace switch to control the detailed request logs written by Google Ads .NET libraries. The default level is set to Off. Logs are generated at both the Error and Information levels. --> <add name="GoogleAds.DetailedRequestLogs" value="Off" /> <!-- Use this trace switch to control the summary request logs written by Google Ads .NET libraries. The default level is set to Off. Logs are generated at both the Error and Information levels. --> <add name="GoogleAds.SummaryRequestLogs" value="Off" /> </switches> <trace autoflush="true" /> </system.diagnostics>在
<configSections>部分下添加以下代码段:<section name="system.diagnostics" type="System.Diagnostics.SystemDiagnosticsSection" />然后,您的
App.config如下所示:<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="GoogleAdsApi" type="System.Configuration.DictionarySectionHandler" /> <section name="system.diagnostics" type="System.Diagnostics.SystemDiagnosticsSection" /> </configSections> <GoogleAdsApi> <!-- Google Ads API settings. --> </GoogleAdsApi> <system.diagnostics> <!-- Logging settings. --> </system.diagnostics> </configuration>