Setting Up Stackdriver Trace for C# ASP.NET Core

Stackdriver Trace can be enabled for ASP.NET core applications using the Google.Cloud.Diagnostics.AspNetCore client library for C#.

Installing the client library

To use the Google.Cloud.Diagnostics.AspNetCore client library in Visual Studio, do the following:

  1. Right-click your solution in Visual Studio and select Manage Nuget packages for solution.

  2. Select the Include prerelease checkbox.

  3. Search for and install the package named Google.Cloud.Diagnostics.AspNetCore.

Configuring the client library

Once the Google.Cloud.Diagnostics.AspNetCore client library is installed, complete the following 4 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. Add this code to your web application's appsettings.json file and update YOUR-GOOGLE-PROJECT-ID to be your project ID or number:

      "Stackdriver": {
        "ProjectId": "YOUR-GOOGLE-PROJECT-ID",
        "ServiceName": "NAME-OF-YOUR-SERVICE",
        "Version": "VERSION-OF-YOUR-SERVICE"
  3. 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.

  4. 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.
                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?}");

A sampling of the HTTP requests received by your application will now be traced automatically. You can also initiate traces from your application as demonstrated below in the sample application for ASP.NET core.

Running on Google Cloud Platform

The Google.Cloud.Diagnostics.AspNetCore client library should work without the need to manually provide authentication credentials for instances running on Google Cloud Platform, as long as the Stackdriver Trace API access scope is enabled on that instance.

App Engine

On Google App Engine flexible environment, the Stackdriver Trace API access scope is enabled by default, and the Google.Cloud.Diagnostics.AspNetCore client library can be used without needing to provide credentials or a project ID.

On Google App Engine standard environment, C# is not currently supported.

Kubernetes Engine

On GKE, add the trace.append OAuth access scope when creating the cluster:

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

You cannot change the access scopes of a cluster after creation.

Compute Engine

For Google Compute Engine instances, you need to explicitly enable the trace.append Stackdriver Trace API access scope for each instance. When creating a new instance through the Google Cloud Platform Console, you can do this under Identity and API access: Use the Compute Engine default service account and select "Allow full access to all Cloud APIs" under Access scopes.

To use something other than the Compute Engine default service account see the docs for Creating and Enabling Service Accounts for Instances and the Running elsewhere section below. The important thing is that the service account you use has the Cloud Trace Agent role.

Running locally and elsewhere

If your application is running outside of Google Cloud Platform, such as locally, on-premises, or on another cloud provider, you can still use Stackdriver Trace, provided that you supply a project ID and credentials to the Google.Cloud.Diagnostics.AspNetCore client library.

Project ID

Set the project ID that is passed to the Google.Cloud.Diagnostics.AspNetCore client library by entering your project ID into the appsettings.json file as described above in step #2 of the Configuring the client library section.


Google Cloud Platform client libraries use a strategy called Application Default Credentials (ADC) to find your application's credentials. You can provide credentials to the Google.Cloud.Diagnostics.AspNetCore client library by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable:

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS=path-to-private-key-for-your-service-account


set GOOGLE_APPLICATION_CREDENTIALS=path-to-private-key-for-your-service-account



For more information, see Providing credentials to your application.

Sample Stackdriver 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 GCP Console Trace Viewer.

Go to the Trace Viewer page

Was this page helpful? Let us know how we did:

Send feedback about...

Stackdriver Trace
Need help? Visit our support page.