Backtrace's integration with C# applications allows customers to capture and report handled and unhandled C# exceptions to their Backtrace instance, instantly offering the ability to prioritize and debug software errors.
$ dotnet add package BacktraceBacktrace's integration with C# applications allows customers to capture and report handled and unhandled C# exceptions to their Backtrace instance, instantly offering the ability to prioritize and debug software errors.
// replace with your universe name and token
var backtraceCredentials =
new BacktraceCredentials(@"https://submit.backtrace.io/universe-name/token/json");
var backtraceClient = new BacktraceClient(backtraceCredentials);
try{
//throw exception here
}
catch(Exception exception){
await backtraceClient.SendAsync(new BacktraceReport(exception));
}
Visual Studio you can use .NET Core command line interface, see installation guide hereThe Backtrace library is available on NuGet. You can read more about NuGet and how to download the packages here
You can install Backtrace via NuGet using the following commands:
Windows NuGet CLI:
Install-Package Backtrace
Linux/Mac OS X .NET Core CLI:
dotnet add package Backtrace
First create a BacktraceCredential instance with your Backtrace endpoint URL (e.g. https://xxx.sp.backtrace.io:6098) and submission token, and supply it as a parameter in the BacktraceClient constructor:
var credentials = new BacktraceCredentials("backtrace_endpoint_url", "token");
var backtraceClient = new BacktraceClient(credentials);
For more advanced usage of BacktraceClient, you can supply BacktraceClientConfiguration as a parameter. See the following example:
var credentials = new BacktraceCredentials("backtrace_endpoint_url", "token");
var configuration = new BacktraceClientConfiguration(credentials){
ClientAttributes = new Dictionary<string, object>() {
{ "attribute_name", "attribute_value" } },
ReportPerMin = 3,
}
var backtraceClient = new BacktraceClient(configuration);
For more information on BacktraceClientConfiguration parameters please see Architecture.
Notes:
reportPerMin is equal to 0, there is no limit on the number of error reports per minute. When the reportPerMin cap is reached, BacktraceClient.Send/BacktraceClient.SendAsync method will return false,WebProxy object to BacktraceCredentials object. We will try to use WebProxy object when user pass it to Backtrace. To setup proxy use property Proxy,BacktraceClient allows you to unpack AggregateExceptions and send only exceptions that are available in InnerException property of AggregateException. By default BacktraceClient will send AggregateException information to Backtrace server. To avoid sending these reports, please override UnpackAggregateException and set value to true.BacktraceClient allows you to customize the initialization of BacktraceDatabase for local storage of error reports by supplying a BacktraceDatabaseSettings parameter, as follows:
var dbSettings = new BacktraceDatabaseSettings("databaseDirectory"){
MaxRecordCount = 100,
MaxDatabaseSize = 1000,
AutoSendMode = true,
RetryBehavior = Backtrace.Types.RetryBehavior.ByInterval
};
var database = new BacktraceDatabase(dbSettings);
var credentials = new BacktraceCredentials("backtrace_endpoint_url", "token");
var configuration = new BacktraceClientConfiguration(credentials);
var backtraceClient = new BacktraceClient(configuration, database);
Notes:
databaseDirectory directory is supplied, the Backtrace library will generate and attach a minidump to each error report automatically. Otherwise, BacktraceDatabase will be disabled,backtraceClient.MiniDumpType to MiniDumpType.None if you don't want to generate minidump files.Backtrace C# library allows you to aggregate the same reports. By using Backtrace deduplication mechanism you can aggregate the same reports and send only one message to Backtrace Api. As a developer you can choose deduplication options. Please use DeduplicationStrategy enum to setup possible deduplication rules or copy example below to setup deduplication strategy:
var dbSettings = new BacktraceDatabaseSettings(path)
{
DeduplicationStrategy = DeduplicationStrategy.LibraryName | DeduplicationStrategy.Classifier | DeduplicationStrategy.Message,
}
Deduplication strategy enum types:
To combine all possible deduplication strategies please use code below:
DeduplicationStrategy = DeduplicationStrategy.LibraryName | DeduplicationStrategy.Classifier | DeduplicationStrategy.Message
Notes:
BacktraceDatabase will store number of the same reports in counter file.BacktraceReport Fingerprint and Factor properties. Fingerprint property will overwrite deduplication algorithm result. Factor property will change hash generated by deduplication algorithm.BacktraceDatabase methods allows you to use aggregated diagnostic data together. You can check Hash property of BacktraceDatabaseRecord to check generated hash for diagnostic data and Counter to check how much the same records we detect.BacktraceDatabase Count method will return number of all records stored in database (included deduplicated records),BacktarceDatabase Delete method will remove record (with multiple deduplicated records) at the same time.GenerateHash delegate available in BacktraceDatabase object. When you add your own method implementation, BacktraceDatabase won't use default deduplication mechanism.BacktraceClient.Send/BacktraceClient.SendAsync method will send an error report to the Backtrace endpoint specified. There Send method is overloaded, see examples below:
The BacktraceReport class represents a single error report. (Optional) You can also submit custom attributes using the attributes parameter, or attach files by supplying an array of file paths in the attachmentPaths parameter.
try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(
exception: exception,
attributes: new Dictionary<string, object>() { { "key", "value" } },
attachmentPaths: new List<string>() { @"file_path_1", @"file_path_2" }
);
var result = backtraceClient.Send(backtraceReport);
}
Notes:
BacktraceClient with BacktraceDatabase and your application is offline or you pass invalid credentials to BacktraceClient, reports will be stored in database directory path,SendAsync method,false to reflectionMethodName. By default this value is equal to true,BacktraceReport allows you to change default fingerprint generation algorithm. You can use Fingerprint property if you want to change fingerprint value. Keep in mind - fingerprint should be valid sha256 string,BacktraceReport allows you to change grouping strategy in Backtrace server. If you want to change how algorithm group your reports in Backtrace server please override Factor property,Fingerprint will overwrite BacktraceReport deduplication strategy! In this case two different reports will use the same hash in deduplication algorithm, that could cause data lost,Factor can change a result from deduplication algorithm. Hash generated by deduplication model properties will include Factor value.If you want to use Fingerprint and Factor property you have to override default property values. See example below to check how to use these properties:
try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(...){
FingerPrint = "sha256 string",
Factor = exception.GetType().Name
};
....
}
For developers that use .NET 4.5+ and .NET Standard we recommend using SendAsync method, which uses asynchronous Tasks. Both Send and SendAsync method returns BacktraceResult. See example below:
try
{
//throw exception here
}
catch (Exception exception)
{
var report = new BacktraceReport(
exception: exception,
attributes: new Dictionary<string, object>() { { "key", "value" } },
attachmentPaths: new List<string>() { @"file_path_1", @"file_path_2" }
);
var result = await backtraceClient.SendAsync(backtraceReport);
}
BacktraceClient can also automatically create BacktraceReport given an exception or a custom message using the following overloads of the BacktraceClient.Send method:
try
{
//throw exception here
}
catch (Exception exception)
{
//use extension method
var report = exception.ToBacktraceReport();
backtraceClient.Send(report);
//pass exception to Send method
backtraceClient.Send(exception);
//pass your custom message to Send method
await backtraceClient.SendAsync("Message");
}
BacktraceClient allows you to attach your custom event handlers. For example, you can trigger actions before the Send method:
//Add your own handler to client API
backtraceClient.BeforeSend =
(Model.BacktraceData model) =>
{
var data = model;
//do something with data for example:
data.Attributes.Add("eventAtrtibute", "EventAttributeValue");
if(data.Classifier == null || !data.Classifier.Any())
{
data.Attachments.Add("path to attachment");
}
return data;
};
BacktraceClient currently supports the following events:
BeforeSendAfterSendRequestHandlerOnReportStartOnClientReportLimitReachedOnUnhandledApplicationExceptionOnServerResponseOnServerErrorBacktraceClient also supports reporting of unhandled application exceptions not captured by your try-catch blocks. To enable reporting of unhandled exceptions:
backtraceClient.HandleApplicationException();
Unhandled application exception handler will store your report in database. In case if you won't see your report in Backtrace, you will have to relaunch your application.
You can extend BacktraceBase to create your own Backtrace client and error report implementation. You can refer to BacktraceClient for implementation inspirations.
BacktraceReport is a class that describe a single error report. Keep in mind that BacktraceClient uses CallingAssembly method to retrieve information about your application.
BacktraceClient is a class that allows you to instantiate a client instance that interacts with BacktraceApi. This class sets up connection to the Backtrace endpoint and manages error reporting behavior (for example, saving minidump files on your local hard drive and limiting the number of error reports per minute). BacktraceClient extends BacktraceBase class.
BacktraceClient takes a BacktraceClientConfiguration parameter, which has the following properties:
Credentials - the BacktraceCredentials object to use for connection to the Backtrace server.ClientAttributes - custom attributes to be submitted to Backtrace alongside the error report.ReportPerMin - A cap on the number of reports that can be sent per minute. If ReportPerMin is equal to zero then there is no cap.BacktraceData is a serializable class that holds the data to create a diagnostic JSON to be sent to the Backtrace endpoint via BacktraceApi. You can add additional pre-processors for BacktraceData by attaching an event handler to the BacktraceClient.BeforeSend event. BacktraceData require BacktraceReport and BacktraceClient client attributes.
BacktraceApi is a class that sends diagnostic JSON to the Backtrace endpoint. BacktraceApi is instantiated when the BacktraceClient constructor is called. You use the following event handlers in BacktraceApi to customize how you want to handle JSON data:
RequestHandler - attach an event handler to this event to override the default BacktraceApi.Send method. A RequestHandler handler requires 3 parameters - uri, header and formdata bytes. Default Send method won't execute when a RequestHandler handler is attached.OnServerError - attach an event handler to be invoked when the server returns with a 400 bad request, 401 unauthorized or other HTTP error codes.OnServerResponse - attach an event handler to be invoked when the server returns with a valid response.BacktraceApi can send synchronous and asynchronous reports to the Backtrace endpoint. To enable asynchronous report (default is synchronous) you have to set AsynchronousRequest property to true.
BacktraceResult is a class that holds response and result from a Send or SendAsync call. The class contains a Status property that indicates whether the call was completed (OK), the call returned with an error (ServerError), the call was aborted because client reporting limit was reached (LimitReached), or the call wasn't needed because developer use UnpackAggregateException property with empty AggregateException object (Empty). Additionally, the class has a Message property that contains details about the status. Note that the Send call may produce an error report on an inner exception, in this case you can find an additional BacktraceResult object in the InnerExceptionResult property.
BacktraceDatabase is a class that stores error report data in your local hard drive. If DatabaseSettings dones't contain a valid DatabasePath then BacktraceDatabase won't generate minidump files and store error report data.
BacktraceDatabase stores error reports that were not sent successfully due to network outage or server unavailability. BacktraceDatabase periodically tries to resend reports
cached in the database. In BacktraceDatabaseSettings you can set the maximum number of entries (MaxRecordCount) to be stored in the database. The database will retry sending
stored reports every RetryInterval seconds up to RetryLimit times, both customizable in the BacktraceDatabaseSettings.
BacktraceDatabaseSettings has the following properties:
DatabasePath - the local directory path where BacktraceDatabase stores error report data when reports fail to sendMaxRecordCount - Maximum number of stored reports in Database. If value is equal to 0, then there is no limit.MaxDatabaseSize - Maximum database size in MB. If value is equal to 0, there is no limit.AutoSendMode - if the value is true, BacktraceDatabase will automatically try to resend stored reports. Default is false.RetryBehavior - - RetryBehavior.ByInterval - Default. BacktraceDatabase will try to resend the reports every time interval specified by RetryInterval. - RetryBehavior.NoRetry - Will not attempt to resend reportsRetryInterval - the time interval between retries, in seconds.RetryLimit - the maximum number of times BacktraceDatabase will attempt to resend error report before removing it from the database.If you want to clear your database or remove all reports after send method you can use Clear, Flush and FlushAsync methods.
ReportWatcher is a class that validate send requests to the Backtrace endpoint. If reportPerMin is set in the BacktraceClient constructor call, ReportWatcher will drop error reports that go over the limit. BacktraceClient check rate limit before BacktraceApi generate diagnostic json.
You can use this Backtrace library with Xamarin if you change your HttpClient Implementation to Android. To change HttpClient settings, navigate to Android Options under Project Settings and click on Advanced button.
See release notes here.