设置适用于 C# ASP.NET Core 的 Cloud Trace

您可以使用适用于 C# 的 Google.Cloud.Diagnostics.AspNetCore 客户端库为 ASP.NET Core 应用启用 Trace。

安装客户端库

按照 nuget.org 中的说明安装该库。

配置客户端库

安装 Google.Cloud.Diagnostics.AspNetCore 客户端库后,请完成以下步骤以启用和配置 Trace:

  1. 将以下 using 指令添加到应用的 Startup.cs 文件中:

    
    using Google.Cloud.Diagnostics.AspNetCore;
    using Google.Cloud.Diagnostics.Common;
    

  2. appsettings.json 文件中输入您的 Google Cloud 项目 ID,以设置传递到 Google.Cloud.Diagnostics.AspNetCore 客户端库的 Google Cloud 项目 ID。在以下示例中,将 YOUR-GOOGLE-PROJECT-ID 替换为您的 Google Cloud 项目 ID 或编号:

    {
      "Stackdriver": {
        "ProjectId": "YOUR-GOOGLE-PROJECT-ID",
        "ServiceName": "NAME-OF-YOUR-SERVICE",
        "Version": "VERSION-OF-YOUR-SERVICE"
      }
    }
  3. 创建名为 StackdriverOptions.cs 且包含以下内容的新文件:

    /*
     * Copyright (c) 2017 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not
     * use this file except in compliance with the License. You may obtain a copy of
     * the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     * License for the specific language governing permissions and limitations under
     * the License.
     */
    
    namespace Stackdriver
    {
        public class StackdriverOptions
        {
            public string ProjectId { get; set; }
            public string ServiceName { get; set; }
            public string Version { get; set; }
        }
    }
    
  4. 在应用的 Startup.cs 文件中创建或修改 ConfigureServices 方法,使其调用 services.AddGoogleTrace()

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
                services.Configure<StackdriverOptions>(
                    Configuration.GetSection("Stackdriver"));
                services.AddGoogleExceptionLogging(options =>
                {
                    options.ProjectId = Configuration["Stackdriver:ProjectId"];
                    options.ServiceName = Configuration["Stackdriver:ServiceName"];
                    options.Version = Configuration["Stackdriver:Version"];
                });
    
                // Add trace service.
                services.AddGoogleTrace(options =>
                {
                    options.ProjectId = Configuration["Stackdriver:ProjectId"];
                    options.Options = TraceOptions.Create(
                        bufferOptions: BufferOptions.NoBuffer());
                });
    
                // Add framework services.
                services.AddMvc();
            }
    

  5. 在应用的 Startup.cs 文件中修改 Configure 方法并调用 app.UseGoogleTrace(),然后调用 app.UseStaticFile()app.UseMvc()

            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                // Configure logging service.
                loggerFactory.AddGoogle(app.ApplicationServices, Configuration["Stackdriver:ProjectId"]);
                var logger = loggerFactory.CreateLogger("testStackdriverLogging");
                // Write the log entry.
                logger.LogInformation("Stackdriver sample started. This is a log message.");
                // Configure error reporting service.
                app.UseGoogleExceptionLogging();
                // Configure trace service.
                app.UseGoogleTrace();
    
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
    

Trace 现在已配置为对您的应用收到的 HTTP 请求进行采样。如需从应用启动跟踪记录,请参阅 ASP.NET core 示例应用

配置您的平台

您可以在 Google Cloud 和其他平台上使用 Cloud Trace。

在 Google Cloud 上运行

当您的应用在 Google Cloud 上运行时,您无需向客户端库提供服务帐号形式的身份验证凭据。但是,您需要确保 Google Cloud Platform 已启用 Cloud Trace API 访问权限范围

对于以下配置,默认的访问权限范围设置会启用 Cloud Trace API:

  • App Engine 柔性环境
  • Google Kubernetes Engine (GKE)

  • Compute Engine

如果您使用自定义访问权限范围,则必须确保已启用 Cloud Trace API 访问权限范围。对于 gcloud 用户,请使用 --scopes 标志指定访问权限范围,并添加 trace.append Cloud Trace API 访问权限范围。例如,如需创建仅启用了 Cloud Trace API 的 GKE 集群,请执行以下操作:

gcloud container clusters create example-cluster-name --scopes=https://www.googleapis.com/auth/trace.append

在本地和其他位置运行

如果您的应用在 Google Cloud 之外运行,则必须向客户端库提供服务帐号形式的身份验证凭据。该服务帐号必须包含 Cloud Trace Agent 角色。如需查看说明,请参阅创建服务帐号

Google Cloud 客户端库会使用应用默认凭据 (ADC) 查找应用的凭据。您可以通过设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量来提供这些凭据:

Linux/macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"

ASP.NET core 的 Trace 应用示例

public class TraceController : Controller
{
    // This incoming HTTP request should be captured by Trace.
    public IActionResult Index([FromServices] IManagedTracer tracer)
    {
        using (tracer.StartSpan(nameof(Index)))
        {
            var traceHeaderHandler = new TraceHeaderPropagatingHandler(() => tracer);
            var response = TraceOutgoing(traceHeaderHandler);
            ViewData["text"] = response.Result.ToString();
            return View();
        }
    }

    // This outgoing HTTP request should be captured by Trace.
    public async Task<string> TraceOutgoing(TraceHeaderPropagatingHandler traceHeaderHandler)
    {
        // Add a handler to trace outgoing requests and to propagate the trace header.
        using (var httpClient = new HttpClient(traceHeaderHandler))
        {
            string url = "https://www.googleapis.com/discovery/v1/apis";
            using (var response = await httpClient.GetAsync(url))
            {
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}

查看跟踪记录

部署后,您可以在 Cloud Console 跟踪记录查看器中查看跟踪记录。

转到“跟踪记录查看器”页面

问题排查

如需了解如何排查 Cloud Trace 的问题,请转到“问题排查”页面

资源