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 directive to your application's Startup.cs file:

    using Google.Cloud.Diagnostics.AspNetCore;

  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 and then add the following code:

    // Add trace service.
    services.AddGoogleTrace(options => {
        options.ProjectId = Configuration["Stackdriver:ProjectId"];
        options.Options = TraceOptions.Create(
            bufferOptions: BufferOptions.NoBuffer());
    });
    

  4. Edit the Configure method in your application's Startup.cs file and add the following code:

    // Configure trace service.
    app.UseGoogleTrace();
    

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.

Container Engine

On Google Container Engine, add the trace.append OAuth scope when creating the cluster:

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

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-premise, 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.

Credentials

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 Mac OS X

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

Windows

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

Powershell:

    $env: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 = "https://www.googleapis.com/discovery/v1/apis";
            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 Platform Console Trace Viewer.

Go to the Trace Viewer page

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Stackdriver Trace