Setting up Cloud Trace for C# ASP.NET Core

You can enable Trace for ASP.NET core applications by using the Google.Cloud.Diagnostics.AspNetCore client library for C#.

Installing the client library

Follow the instructions at to install the library.

Configuring the client library

After the Google.Cloud.Diagnostics.AspNetCore client library is installed, complete the following steps to enable and configure Trace:

  1. Add the following using directives to your application's Startup.cs file:

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

  2. Set the Google Cloud project ID that is passed to the Google.Cloud.Diagnostics.AspNetCore client library by entering your Google Cloud project ID in the appsettings.json file. In the following sample, replace YOUR-GOOGLE-PROJECT-ID with your Google Cloud project ID or number:

      "Stackdriver": {
        "ProjectId": "YOUR-GOOGLE-PROJECT-ID",
        "ServiceName": "NAME-OF-YOUR-SERVICE",
        "Version": "VERSION-OF-YOUR-SERVICE"
  3. Create a new file named StackdriverOptions.cs with the following content:

     * 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
     * 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. Create or edit the ConfigureServices method in your application's Startup.cs file so that it calls services.AddGoogleTrace():

            public void ConfigureServices(IServiceCollection services)
                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.

  5. Edit the Configure method in your application's Startup.cs file and call app.UseGoogleTrace() before calling app.UseStaticFile() and 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.
                // Configure trace service.
                app.UseMvc(routes =>
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");

Trace is now configured to sample the HTTP requests received by your application. To initiate traces from your application, see sample application for ASP.NET core.

Configure your platform

You can use Cloud Trace on Google Cloud and other platforms.

Running on Google Cloud

When your application is running on Google Cloud, you don't need to provide authentication credentials in the form of a service account to the client library. However, you do need to ensure that your Google Cloud platform has the Cloud Trace API access scope enabled.

For a list of supported Google Cloud environments, see Environment support.

For the following configurations, the default access-scope settings enable the Cloud Trace API:

  • App Engine flexible environment
  • Google Kubernetes Engine (GKE)

  • Compute Engine

  • Cloud Run

If you use custom access scopes, then you must ensure that Cloud Trace API access scope is enabled:

  • For information about how to configure the access scopes for your environment by using the Google Cloud Console, see Configuring your Google Cloud project.

  • For gcloud users, specify access scopes using the --scopes flag and include the trace.append Cloud Trace API access scope. For example, to create a GKE cluster with only the Cloud Trace API enabled, do the following:

    gcloud container clusters create example-cluster-name --scopes=

Running locally and elsewhere

If your application is running outside of Google Cloud, then you must provide authentication credentials in the form of a service account to the client library. The service account must contain the Cloud Trace agent role. For instructions, see Creating a service account.

Google Cloud client libraries use Application Default Credentials (ADC) to find your application's credentials. You provide these credentials by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable:


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


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



Sample Trace application for ASP.NET core

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 = "";
            using (var response = await httpClient.GetAsync(url))
                return await response.Content.ReadAsStringAsync();

Viewing the traces

After deployment, you can view the traces in the Cloud Console Trace Viewer.

Go to the Trace Viewer page


For information on troubleshooting issues with Cloud Trace, go to the Troubleshooting page.