Setting up Stackdriver 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

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

  1. In Visual Studio, right-click your solution 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 .

For more information, see Google.Cloud.Diagnostics.AspNetCore .

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. Add the following 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.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();
            }
    

  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.
                loggerFactory.AddGoogle(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 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.

Running on Google Cloud Platform

You don't need to provide authentication credentials for instances running on Google Cloud Platform, provided Stackdriver Trace API access scope is enabled on that instance. However, we recommend setting the broadest possible access scope for your instance and then using Cloud Identity and Access Management to restrict access.

App Engine flexible environment

On 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 providing credentials or a project ID.

App Engine standard environment

On App Engine standard, C# isn't currently supported.

GKE

To use Trace with GKE, add the trace.append OAuth access scope when you create your cluster.

To create a cluster using gcloud, do the following:

  1. (Optional) Update gcloud to the latest version:
    gcloud components update
  2. Set your default project ID:
    gcloud config set project [PROJECT_ID]
  3. If you're working with zonal clusters, set your default compute zone:
    gcloud config set compute/zone [COMPUTE_ZONE]
  4. If you're working with regional clusters, set your default compute region:
    gcloud config set compute/region [COMPUTE_REGION]
  5. Issue the create command:
    gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/trace.append

For more detailed information on creating a cluster, see Creating a cluster.

Compute Engine

For Compute Engine VM instances, you need to explicitly enable the trace.append Stackdriver Trace API access scope for each VM instance. When creating a new instance through the Google Cloud Platform Console, select the following values in the Identity and API access section of the Create an instance panel:

  1. Select Compute Engine default service account for Service account
  2. Select Allow full access to all Cloud APIs for Access Scopes

To use something other than the Compute Engine default service account see the Creating and enabling service accounts for instances and Running locally and elsewhere sections. The important thing is that the service account you use has the Cloud Trace Agent role.

Running locally and elsewhere

To run Stackdriver Trace outside of GCP you must supply your GCP project ID and appropriate service account credentials directly to Google.Cloud.Diagnostics.AspNetCore client library . Your service account must contain the Cloud Trace agent role. For instructions, see Creating a service account.

Project ID

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

Credentials

GCP client libraries use Application default credentials (ADC) to find your application's credentials. You provide credentials to the Google.Cloud.Diagnostics.AspNetCore client library by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable:

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"

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 = "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 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.