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

Follow the instructions at nuget.org 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
     *
     * 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. 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();
            }
    

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

Configuring your platform

You can use Trace on Google Cloud and when your application runs outside of Google Cloud.

Running on Google Cloud

When your application is running on Google Cloud, your application is automatically authenticated and you don't need to provide authentication credentials. However, you do need to ensure that your Google Cloud platform has the Stackdriver Trace API access scope enabled.

For the following configurations, the default settings for the access scopes have the Stackdriver Trace API enabled:

  • App Engine flexible environment
  • Google Kubernetes Engine

  • Compute Engine

If you use custom access scopes, then you must ensure that Stackdriver Trace API access scope enabled. For gcloud users, specify access scopes using the --scopes flag and include the trace.append Stackdriver Trace API access scope. For example, to create a GKE cluster with only the Stackdriver Trace API enabled, do the following:

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

Running locally and elsewhere

When your application is running outside of Google Cloud, 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:

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 Cloud Console Trace Viewer.

Go to the Trace Viewer page

Resources

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

Send feedback about...

Stackdriver Trace Documentation
Need help? Visit our support page.