Google.Cloud.Diagnostics.AspNet
Google.Cloud.Diagnostics.AspNet
is an ASP.NET instrumentation library for Google Stackdriver.
It allows for simple integration of Stackdriver into ASP.NET applications with minimal code changes.
Google.Cloud.Diagnostics.AspNet
currently supports Stackdriver Error Reporting and Stackdriver Trace.
Note:
This documentation is for version 4.0.0
of the library.
Some samples may not work with other versions.
Installation
Install the Google.Cloud.Diagnostics.AspNet
package from NuGet. Add it to
your project in the normal way (for example by right-clicking on the
project in Visual Studio and choosing "Manage NuGet Packages...").
Authentication
When running on Google Cloud Platform, no action needs to be taken to authenticate.
Otherwise, the simplest way of authenticating your API calls is to
download a service account JSON file then set the GOOGLE_APPLICATION_CREDENTIALS
environment variable to refer to it.
The credentials will automatically be used to authenticate. See the Getting Started With
Authentication guide for more details.
Note
The Google.Cloud.Diagnostics.AspNet package attempts to collect the filename and line number when entries are collected. However, to be able to collect this information PDBs must be included with the deployed code.
Getting started
Registering Error Reporting (Web Api)
private static void Register(HttpConfiguration config)
{
// Add a catch all for the uncaught exceptions.
// Replace ProjectId with your Google Cloud Project ID.
// Replace Service with a name or identifier for the service.
// Replace Version with a version for the service.
config.Services.Add(typeof(System.Web.Http.ExceptionHandling.IExceptionLogger),
ErrorReportingExceptionLogger.Create(ProjectId, Service, Version));
// Any other actions your app might need.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Log Exceptions (Web Api)
public class HomeController : ApiController
{
// On this sample, we explicitly create an instance of the Web Api specific
// GoogleWebApiExceptionLogger.
// This is a dependency that you will probably want to inject
// using the dependency injection mechanism of your choice.
IWebApiExceptionLogger exceptionLogger = GoogleWebApiExceptionLogger.Create(
// Replace ProjectId with your Google Cloud Project ID.
// Replace Service with a name or identifier for the service.
// Replace Version with a version for the service.
ProjectId, Service, Version);
/// <summary>This action method catches and logs an <see cref="Exception"/> using the
/// Web Api specific <see cref="GoogleWebApiExceptionLogger"></summary>
[HttpGet]
public string CatchesAndLogsExceptions(string id)
{
try
{
// Do something which happens to throw an Exception
DoSomething(id);
}
catch (Exception e)
{
exceptionLogger.Log(e, ActionContext);
}
return "Something done succesfully.";
}
// This is normally not required, but ensures that "DoSomething" is in the stack
// trace. The method is otherwise inlined by the JIT compiler for release builds in
// some environments.
[MethodImpl(MethodImplOptions.NoInlining)]
private void DoSomething(string id)
{
throw new Exception(id);
}
}
Registering Error Reporting (MVC)
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
string projectId = "[Google Cloud Platform project ID]";
string serviceName = "[Name of service]";
string version = "[Version of service]";
// Add a catch all for the uncaught exceptions.
filters.Add(ErrorReportingExceptionFilter.Create(projectId, serviceName, version));
}
Log Exceptions (MVC)
string projectId = "[Google Cloud Platform project ID]";
string serviceName = "[Name of service]";
string version = "[Version of service]";
var exceptionLogger = GoogleExceptionLogger.Create(projectId, serviceName, version);
try
{
string scores = File.ReadAllText(@"C:\Scores.txt");
Console.WriteLine(scores);
}
catch (IOException e)
{
exceptionLogger.Log(e);
}
Initializing Tracing
public class Global : HttpApplication
{
public override void Init()
{
base.Init();
string projectId = "[Google Cloud Platform project ID]";
// Trace a sampling of incoming Http requests.
CloudTrace.Initialize(this, projectId);
}
}
Trace Outgoing HTTP Requests
// Add a handler to trace outgoing requests and to propagate the trace header.
var traceHeaderHandler = CloudTrace.CreateTracingHttpMessageHandler();
using (var httpClient = new HttpClient(traceHeaderHandler))
{
return await httpClient.GetAsync("https://weather.com/");
}
Manual Tracing
// Manually trace a specific operation.
using (CloudTrace.Tracer.StartSpan("hello-world"))
{
Console.Out.WriteLine("Hello, World!");
}
// Manually trace a specific Action or Func<T>.
CloudTrace.Tracer.RunInSpan(
() => Console.Out.WriteLine("Hello, World!"),
"hello-world");