配置日志记录

.NET 客户端库会记录向 Google Ads API 发出的请求、响应和摘要消息。日志可以写入自定义 TraceListener或自定义 ILogger 实例。

TraceListener

您可以在发出任何 API 调用之前,通过在 Main 方法中添加以下行来启用向 TraceListener 的日志记录:

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 调用中提取

您可以使用带有 TrailingMetadataHandler 的自定义 CallSettings 从常规一元调用中捕获请求 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 调用中提取

对于流式 API 调用,请求 ID 会作为响应对象的一部分返回。例如,您可以按如下方式获取 SearchStream 调用的请求 ID:

// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V26.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 调用失败时,请求 ID 都会作为 GoogleAdsException 异常的一部分返回:

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 目标构建的应用不支持此功能。

如需使用此功能,请对配置文件进行以下更改:

  1. 在 <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>
    
  2. 在 <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>