New Relic's .NET agent includes an API that allows you to extend the agent's standard functionality. For example, you can use the .NET agent API to:
- Customize your app name
- Create custom transaction parameters
- Report custom errors and metrics
You can also customize some of the .NET agent's default behavior by adjusting configuration settings or using custom instrumentation.
Requirements
To use the .NET agent API, make sure you have the latest .NET agent release. Then, add a reference to the agent in your project using one of the two options below:
Add a reference to
NewRelic.Api.Agent.dll
to your project.OR
View and download the API package from the NuGet Package Library.
List of API calls
The following list contains the different calls you can make with the API, including syntax, requirements, functionality, and examples:
Syntax
NewRelic.Api.Agent.NewRelic.DisableBrowserMonitoring([boolean $override])
Disable automatic injection of browser monitoring snippet on specific pages.
Requirements
- Compatible with all agent versions.
- Must be called inside a transaction.
Description
Add this call to disable the automatic injection of scripts on specific pages. You can also add an optional override to disable both manual and automatic injection. In either case, put this API call as close as possible to the top of the view in which you want browser disabled.
Tip
Compare GetBrowserTimingHeader()
, which adds the browser script to the page.
Parameters
Parameter | Description |
---|---|
boolean | Optional. When |
Examples
Disable automatic injection
This example disables only the automatic injection of the snippet:
NewRelic.Api.Agent.NewRelic.DisableBrowserMonitoring();
Disable automatic and manual injection
This example disables both automatic and manual injection of the snippet:
NewRelic.Api.Agent.NewRelic.DisableBrowserMonitoring(true);
Syntax
NewRelic.Api.Agent.NewRelic.GetAgent()
Get access to the agent via the IAgent
interface.
Requirements
- Agent version 8.9 or higher.
- Compatible with all app types.
Description
Get access to agent API methods via the IAgent
interface.
Return values
An implementation of IAgent providing access to the IAgent API.
Examples
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();
Syntax
NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader();NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader(string nonce);
Generate a browser monitoring HTML snippet to instrument end-user browsers.
Requirements
- Compatible with all agent versions.
- Must be called inside a transaction.
Description
Returns an HTML snippet used to enable . The snippet instructs the browser to fetch a small JavaScript file and start the page timer. You can then insert the returned snippet into the header of your HTML webpages. For more information, see Adding apps to browser monitoring.
Tip
Compare DisableBrowserMonitoring()
, which disables the browser script on a page.
Parameters
Parameter | Description |
---|---|
string | The per-request, cryptographic nonce used by Content Security Policy policies. |
Tip
This API call requires updates to security allow lists. For more information about Content Security Policy (CSP) considerations, visit the browser monitoring compatibility and requirements page.
Return values
An HTML string to be embedded in a page header.
Examples
<html><head> <%= NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader()%> ...</head><body>...
<html><head> <%= NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader("YOUR_NONCE_VALUE")%> ...</head><body>...
<!DOCTYPE html><html lang="en"><head> @Html.Raw(NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader()) ...</head><body>...
<!DOCTYPE html><html lang="en"><head> @Html.Raw(NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader("YOUR_NONCE_VALUE")) ...</head><body>...
Important
This API is not supported for Blazor Webassembly, because the agent is unable to instrument Webassembly code. The following examples are for Blazor Server applications only. Use the copy-paste method of adding the browser agent to Blazor Webassembly pages.
Important
This API can not be placed in a <HeadContent>
element of a .razor
page. Instead, it should be called from _Layout.cshtml
or an equivalent layout file.
<!DOCTYPE html><html lang="en"><head> @Html.Raw(NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader()) ...</head><body>...
<!DOCTYPE html><html lang="en"><head> @Html.Raw(NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader("YOUR_NONCE_VALUE")) ...</head><body>...
Syntax
NewRelic.Api.Agent.NewRelic.GetLinkingMetadata();
Returns key/value pairs which can be used to link traces or entities.
Requirements
- Agent version 8.19 or higher.
- Compatible with all app types.
Description
The dictionary of key/value pairs returned includes items used to link traces and entities in the APM product. It will only contain items with meaningful values. For instance, if distributed tracing is disabled, trace.id
will not be included.
Return values
Dictionary <string, string>()
returned includes items used to link traces and entities in the APM product.
Examples
NewRelic.Api.Agent.IAgent Agent = NewRelic.Api.Agent.NewRelic.GetAgent();var linkingMetadata = Agent.GetLinkingMetadata();foreach (KeyValuePair<string, string> kvp in linkingMetadata){ Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);}
Syntax
public interface IAgent
Provides access to agent artifacts and methods, such as the currently executing transaction.
Requirements
- Agent version 8.9 or higher.
- Compatible with all app types.
Description
Provides access to agent artifacts and methods, such as the currently executing transaction. To obtain a reference to IAgent
, use GetAgent
.
Properties
Name | Description |
---|---|
CurrentTransaction | Property providing access to the currently executing transaction via the ITransaction interface. Must be called inside a transaction. |
CurrentSpan | Property providing access to the currently executing span via the ISpan interface. |
Examples
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();ITransaction transaction = agent.CurrentTransaction;
Syntax
public interface ITransaction
Provides access to transaction-specific methods in the New Relic API.
Description
Provides access to transaction-specific methods in the New Relic .NET agent API. To obtain a reference to ITransaction
, use the current transaction method available on IAgent
.
The following methods are available on ITransaction
:
Name | Description |
---|---|
| Adds distributed tracing data to an outgoing request (see below for more details). |
| Accepts incoming distributed tracing data from another service (see below for more details). |
| Add contextual information from your application to the current transaction in form of attributes (see below for more details). |
| Provides access to the currently executing span, which provides access to span-specific methods in the New Relic API (see below for more details). |
| Associates a user ID to the current transaction (see below for more details). |
| Allows an unsupported datastore to be instrumented (see below for more details). |
Syntax
void InsertDistributedTraceHeaders(carrier, setter)
Adds distributed tracing data to an outbound message to another instrumented service.
Description
ITransaction.InsertDistributedTraceHeaders
modifies the carrier object that is passed in by adding W3C Trace Context headers and New Relic Distributed Trace headers. The New Relic headers can be disabled with <distributedTracing excludeNewrelicHeader="true" />
in the config.
Parameters
Name | Description |
---|---|
<T> | Required. A key/value pair store where distributed tracing data is inserted. This needs to exist in whatever message object is being passed from the calling service to the called service, via whatever transport is being used. For example, for Azure Service Bus messages, the |
Action<T, string, string> | Required. A user-defined Action to insert tracing data into the carrier. See example below. |
Usage considerations
- Distributed tracing must be enabled.
- This API can only be used within the context of an existing transaction.
Example
You can find a complete example that you can build and run to demonstrate the use of this API here.
// Get a reference to the agent, which lets you get a reference to the current transactionIAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();ITransaction currentTransaction = agent.CurrentTransaction;
// In this example, we are using Azure Service Bus. The `ServiceBusMessage` type has an `ApplicationProperties` property for custom key/value pairs.
// Create the outbound messageServiceBusMessage message = new ("Hello, world!");
// Define the setter Action. The `ApplicationProperties` dictionary is the trace data carrier.var setter = new Action<ServiceBusMessage, string, string>((carrier, key, value) => { carrier.ApplicationProperties?.Set(key, value); });
// Call the API to add the distributed tracing data to the messagecurrentTransaction.InsertDistributedTraceHeaders(message, setter);
// Send the message
Syntax
void AcceptDistributedTraceHeaders(carrier, getter, transportType)
Accepts distributed tracing data from an inbound message from another instrumented service.
Description
ITransaction.AcceptDistributedTraceHeaders
is used to link the spans in a trace by accepting a payload generated by InsertDistributedTraceHeaders
or generated by some other W3C Trace Context compliant tracer. This method accepts the key/value store from an incoming request, looks for W3C Trace Context data, and if not found, falls back to New Relic distributed trace data.
Parameters
Name | Description |
---|---|
<T> | Required. A key/value pair store where distributed tracing data was inserted by the calling service. This needs to exist in whatever message object is being passed from the calling service to the called service, via whatever transport is being used. For example, for Azure Service Bus messages, the |
Func<T, string, IEnumerable<string>> | Required. A user-defined Func to extract tracing data from the carrier. See example below. |
TransportType enum | Required. Describes the transport of the incoming payload (for example |
Usage considerations
- Distributed tracing must be enabled.
- This API can only be used within the context of an existing transaction.
AcceptDistributedTraceHeaders
will be ignored ifInsertDistributedTraceHeaders
orAcceptDistributedTraceHeaders
has already been called for this transaction.
Example
You can find a complete example that you can build and run to demonstrate the use of this API here
// Get a reference to the agent, which lets you get a reference to the current transactionIAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();ITransaction currentTransaction = agent.CurrentTransaction;
// In this example, we are using Azure Service Bus. The `ServiceBusMessage` type has an `ApplicationProperties` property for custom key/value pairs.
// Recieve an incoming message. Assume that `receiver` is a previously-configured `ServiceBusReceiver`ServiceBusReceivedMessage message = await receiver.ReceiveMessageAsync();
// Define the getter Func. The `ApplicationProperties` dictionary is the trace data carrier.IEnumerable<string> Getter(IDictionary<string, object> carrier, string key){ var data = new List<string>(); if (carrier == null) { return data; } object value; if (applicationProperties.TryGetValue(key, out value)) { if (value != null) { data.Add(value.ToString()); } } return data;}
// Call the API to accept the distributed tracing data from the messagecurrentTransaction.AcceptDistributedTraceHeaders(message.ApplicationProperties, Getter, TransportType.Queue);
Syntax
ITransaction AddCustomAttribute(string key, object value)
Adds contextual information about your application to the current transaction in the form of attributes.
This method requires .NET agent version and .NET agent API version 8.24.244.0 or higher. It replaced the deprecated AddCustomParameter
.
Parameters
Parameter | Description |
---|---|
string | Identifies the information being reported. Also known as the name.
|
object | The value being reported. Note: |
.NET type | How the value will be represented |
---|---|
| As an integral value. |
| A decimal-based number. |
| A string truncated after 255-bytes. Empty strings are supported. |
| True or false. |
| A string representation following the ISO-8601 format, including time zone information: Example: |
| A decimal-based number representing number of seconds. |
everything else | The |
Returns
A reference to the current transaction.
Usage considerations
For details about supported data types, see Custom attributes.
Example
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();ITransaction transaction = agent.CurrentTransaction;transaction.AddCustomAttribute("customerName","Bob Smith") .AddCustomAttribute("currentAge",31) .AddCustomAttribute("birthday", new DateTime(2000, 02, 14)) .AddCustomAttribute("waitTime", TimeSpan.FromMilliseconds(93842));
Provides access to the currently executing span, making span-specific methods available within the New Relic API.
Example
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent(); ITransaction transaction = agent.CurrentTransaction; ISpan currentSpan = transaction.CurrentSpan;
Syntax
ITransaction SetUserId(string userId)
Associates a user ID with the current transaction.
This method requires .NET agent and .NET agent API version 10.9.0 or higher.
Parameters
Parameter | Description |
---|---|
string | The User Id to be associated with this transaction.
|
Example
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent(); ITransaction transaction = agent.CurrentTransaction; transaction.SetUserId("BobSmith123");
Syntax
SegmentWrapper? RecordDatastoreSegment(string vendor, string model, string operation, string? commandText = null, string? host = null, string? portPathOrID = null, string? databaseName = null)
Allows an unsupported datastore to be instrumented in the same way as the .NET agent automatically instruments its supported datastores.
This method requires .NET agent and .NET agent API version 10.22.0 or higher.
Parameters
Parameter | Description |
---|---|
string | Datastore vendor name, such as MySQL, MSSQL, or MongoDB. |
string | Table name, or similar identifier in a non-relational datastore. |
string | Operation being performed, such as "SELECT" or "UPDATE" for SQL databases. |
string? | Optional. Query, or similar descriptor in a non-relational datastore. |
string? | Optional. Server hosting the datastore. |
string? | Optional. Port, path, or other identifier, paired with the host to aid in identifying the datastore. |
string? | Optional. Datastore name or similar identifier. |
Returns
IDisposable segment wrapper that both creates and ends the segment automatically.
Example
var transaction = NewRelic.Api.Agent.NewRelic.GetAgent().CurrentTransaction;using (transaction.RecordDatastoreSegment(vendor, model, operation, commandText, host, portPathOrID, databaseName)){ DatastoreWorker();}
Syntax
Public interface ISpan
Provides access to span-specific methods in the New Relic API.
Description
Provides access to span-specific methods in the New Relic .NET agent API. To obtain a reference to ISpan
, use:
- The
CurrentSpan
property onIAgent
(Recommended). - The
CurrentSpan
property onITransaction
.
This section contains descriptions and parameters of ISpan
methods:
Name | Description |
---|---|
| Add contextual information from your application to the current span in form of attributes (see below for more details). |
| Changes the name of the current span/segment/metrics that will be reported to New Relic (see below for more details). |
Adds contextual information about your application to the current span in the form of attributes.
This method requires .NET agent version and .NET agent API version 8.25 or higher.
Syntax
ISpan AddCustomAttribute(string key, object value)
Parameters
Parameter | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
string | Identifies the information being reported. Also known as the name.
| ||||||||||||||||
object | The value being reported. Note:
|
Returns
A reference to the current span.
Usage considerations
For details about supported data types, see the Custom Attributes guide.
Examples
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent(); ISpan currentSpan = agent.CurrentSpan;
currentSpan .AddCustomAttribute("customerName","Bob Smith") .AddCustomAttribute("currentAge",31) .AddCustomAttribute("birthday", new DateTime(2000, 02, 14)) .AddCustomAttribute("waitTime", TimeSpan.FromMilliseconds(93842));
Changes the name of the current segment/span that will be reported to New Relic. For segments/spans resulting from custom instrumentation, the metric name reported to New Relic will be altered as well.
This method requires .NET agent version and .NET agent API version 10.1.0 or higher.
Syntax
ISpan SetName(string name)
Parameters
Parameter | Description |
---|---|
string | The new name for the span/segment. |
Returns
A reference to the current span.
Examples
[Trace]public void MyTracedMethod(){ IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent(); ISpan currentSpan = agent.CurrentSpan;
currentSpan.SetName("MyCustomName");}
Syntax
NewRelic.Api.Agent.NewRelic.IgnoreApdex()
Ignore the current transaction when calculating Apdex.
Requirements
Compatible with all agent versions.
Description
Ignores the current transaction when calculating your Apdex score. This is useful when you have either very short or very long transactions (such as file downloads) that can skew your Apdex score.
Examples
NewRelic.Api.Agent.NewRelic.IgnoreApdex();
Syntax
NewRelic.Api.Agent.NewRelic.IgnoreTransaction()
Do not instrument the current transaction.
Requirements
- Compatible with all agent versions.
- Must be called inside a transaction.
Description
Ignores the current transaction.
Tip
You can also ignore transactions via a custom instrumentation XML file.
Examples
NewRelic.Api.Agent.NewRelic.IgnoreTransaction();
Syntax
NewRelic.Api.Agent.NewRelic.IncrementCounter(string $metric_name)
Increment the counter for a custom metric by 1.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Increment the counter for a custom metric by 1. To view these custom metrics, use the query builder to search metrics and create customizable charts. See also RecordMetric()
and RecordResponseTimeMetric()
.
Important
When creating a custom metric, start the name with Custom/
(for example, Custom/MyMetric
). For more on naming, see Collect custom metrics.
Parameters
Parameter | Description |
---|---|
string | Required. The name of the metric to increment. |
Examples
NewRelic.Api.Agent.NewRelic.IncrementCounter("Custom/ExampleMetric");
Overloads
Notice an error and report to New Relic, along with optional custom attributes.
NewRelic.Api.Agent.NewRelic.NoticeError(Exception $exception);NewRelic.Api.Agent.NewRelic.NoticeError(Exception $exception, IDictionary<TKey, TValue> $attributes);NewRelic.Api.Agent.NewRelic.NoticeError(string $error_message, IDictionary<TKey, TValue> $attributes);NewRelic.Api.Agent.NewRelic.NoticeError(string $error_message, IDictionary<TKey, TValue> $attributes, bool $is_expected);
Requirements
This API call is compatible with:
- All agent versions
- All app types
Description
Notice an error and report it to New Relic along with optional custom attributes. For each transaction, the agent only retains the exception and attributes from the first call to NoticeError()
. You can pass an actual exception, or pass a string to capture an arbitrary error message.
If this method is invoked within a transaction, the agent reports the exception within the parent transaction. If it is invoked outside of a transaction, the agent creates an error trace and categorizes the error in the New Relic UI as a NewRelic.Api.Agent.NoticeError
API call. If invoked outside of a transaction, the NoticeError()
call will not contribute to the error rate of an application.
The agent adds the attributes only to the traced error; it does not send them to New Relic. For more information, see AddCustomAttribute()
.
Errors reported with this API are still sent to New Relic when they are reported within a transaction that results in an HTTP status code, such as a 404
, that is configured to be ignored by agent configuration. For more information, see our documentation about managing errors in APM.
Review the sections below to see examples of how to use this call.
NewRelic.Api.Agent.NewRelic.NoticeError(Exception $exception)
Parameter | Description |
---|---|
Exception | Required. The |
NewRelic.Api.Agent.NewRelic.NoticeError(Exception $exception, IDictionary<TKey, TValue> $attributes)
Parameter | Description |
---|---|
Exception | Required. The |
IDictionary<TKey, TValue> | Specify key/value pairs of attributes to annotate the error message. The |
NewRelic.Api.Agent.NewRelic.NoticeError(string $error_message, IDictionary<TKey, TValue> $attributes)
Parameter | Description |
---|---|
string | Required. Specify a string to report to New Relic as though it's an exception. This method creates both error events and error traces. Only the first 1023 characters are retained in error events, while error traces retain the full message. |
IDictionary<TKey, TValue> | Required (can be null). Specify key/value pairs of attributes to annotate the error message. The |
NewRelic.Api.Agent.NewRelic.NoticeError(string $error_message, IDictionary<TKey, TValue> $attributes, bool $is_expected)
Parameter | Description |
---|---|
string | Required. Specify a string to report to New Relic as though it's an exception. This method creates both error events and error traces. Only the first 1023 characters are retained in error events, while error traces retain the full message. |
IDictionary<TKey, TValue> | Required (can be null). Specify key/value pairs of attributes to annotate the error message. The |
bool | Mark error as expected so that it won't affect Apdex score and error rate. |
Examples
Pass an exception without custom attributes
try{ string ImNotABool = "43"; bool.Parse(ImNotABool);}catch (Exception ex){ NewRelic.Api.Agent.NewRelic.NoticeError(ex);}
Pass an exception with custom attributes
try{ string ImNotABool = "43"; bool.Parse(ImNotABool);}catch (Exception ex){ var errorAttributes = new Dictionary<string, string>() {{"foo", "bar"},{"baz", "luhr"}}; NewRelic.Api.Agent.NewRelic.NoticeError(ex, errorAttributes);}
Pass an error message string with custom attributes
try{ string ImNotABool = "43"; bool.Parse(ImNotABool);}catch (Exception ex){ var errorAttributes = new Dictionary<string, string>{{"foo", "bar"},{"baz", "luhr"}}; NewRelic.Api.Agent.NewRelic.NoticeError("String error message", errorAttributes);}
Pass an error message string without custom attributes
try{ string ImNotABool = "43"; bool.Parse(ImNotABool);}catch (Exception ex){ NewRelic.Api.Agent.NewRelic.NoticeError("String error message", null);}
Pass an error message string and mark it as expected
try{ string ImNotABool = "43"; bool.Parse(ImNotABool);}catch (Exception ex){ NewRelic.Api.Agent.NewRelic.NoticeError("String error message", null, true);}
Syntax
NewRelic.Api.Agent.NewRelic.RecordCustomEvent(string eventType, IEnumerable<string, object> attributeValues)
Records a custom event with the given name and attributes.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Records a custom event with the given name and attributes, which you can query in the query builder. To verify if an event is being recorded correctly, look for the data in dashboards.
Important
- Sending a lot of events can increase the memory overhead of the agent.
- Additionally, posts greater than 1MB (10^6 bytes) in size will not be recorded regardless of the maximum number of events.
- Custom events are limited to 64 attributes.
- For more information about how custom attribute values are processed, see the custom attributes guide.
Parameters
Parameter | Description |
---|---|
string | Required. The name of the event type to record. Strings over 255 characters will result in the API call not being sent to New Relic. The name can only contain alphanumeric characters, underscores |
IEnumerable<string, object> | Required. Specify key/value pairs of attributes to annotate the event. |
Examples
Record values [#record-strings]
var eventAttributes = new Dictionary<string, object>() { {"foo", "bar"}, {"alice", "bob"}, {"age", 32}, {"height", 21.3f}};
NewRelic.Api.Agent.NewRelic.RecordCustomEvent("MyCustomEvent", eventAttributes);
Syntax
NewRelic.Api.Agent.NewRelic.RecordMetric(string $metric_name, single $metric_value)
Records a custom metric with the given name.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Records a custom metric with the given name. To view these custom metrics, use the query builder to search metrics and create customizable charts. See also IncrementCounter()
and RecordResponseTimeMetric()
.
Important
When creating a custom metric, start the name with Custom/
(for example, Custom/MyMetric
).
Parameters
Parameter | Description |
---|---|
string | Required. The name of the metric to record. Only the first 255 characters are retained. |
single | Required. The quantity to record for the metric. |
Examples
Record response time of a sleeping process [#record-stopwatch]
Stopwatch stopWatch = Stopwatch.StartNew();System.Threading.Thread.Sleep(5000);stopWatch.Stop();NewRelic.Api.Agent.NewRelic.RecordMetric("Custom/DEMO_Record_Metric", stopWatch.ElapsedMilliseconds);
Syntax
NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric(string $metric_name, Int64 $metric_value)
Records a custom metric with the given name and response time in milliseconds.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Records the response time in milliseconds for a custom metric. To view these custom metrics, use the query builder to search metrics and create customizable charts. See also IncrementCounter()
and RecordMetric()
.
Important
When creating a custom metric, start the name with Custom/
(for example, Custom/MyMetric
).
Parameters
Parameter | Description |
---|---|
string | Required. The name of the response time metric to record. Only the first 255 characters are retained. |
Int64 | Required. The response time to record in milliseconds. |
Examples
Record response time of a sleeping process [#record-stopwatch]
Stopwatch stopWatch = Stopwatch.StartNew();System.Threading.Thread.Sleep(5000);stopWatch.Stop();NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric("Custom/DEMO_Record_Response_Time_Metric", stopWatch.ElapsedMilliseconds);
Syntax
NewRelic.Api.Agent.NewRelic.SetApplicationName(string $name[, string $name_2, string $name_3])
Set the app name for data rollup.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Set the application name(s) reported to New Relic. For more information about application naming, see Name your .NET application. This method is intended to be called once, during startup of an application.
Important
Updating the app name forces the agent to restart. The agent discards any unreported data associated with previous app names. Changing the app name multiple times during the lifecycle of an application is not recommended due to the associated data loss.
Parameters
Parameter | Description |
---|---|
string | Required. The primary application name. |
string | Optional. Second and third names for app rollup. For more information, see Use multiple names for an app. |
Examples
NewRelic.Api.Agent.NewRelic.SetApplicationName("AppName1", "AppName2");
Syntax
NewRelic.Api.Agent.NewRelic.SetErrorGroupCallback(Func<IReadOnlyDictionary<string,object>, string> errorGroupCallback);
Provide a callback method that takes an IReadOnlyDictionary<string,object>
of attribute data, and returns an error group name.
Requirements
This API call is compatible with:
- Agent version 10.9.0 or higher.
- All app types
Description
Set a callback method that the agent will use to determine the error group name for error events and traces. This name is used in the Errors Inbox to group errors into logical groups.
The callback method must accept a single argument of type IReadOnlyDictionary<string,object>
, and return a string (the error group name). The IReadOnlyDictionary
is a collection of attribute data associated with each error event, including custom attributes.
The exact list of attributes available for each error will vary depending on:
- What application code generated the error
- Agent configuration settings
- Whether any custom attributes were added
However, the following attributes should always exist:
error.class
error.message
stack_trace
transactionName
request.uri
error.expected
An empty string may be returned for the error group name when the error can't be assigned to a logical error group.
Parameters
Parameter | Description |
---|---|
Func<IReadOnlyDictionary<string,object>,string> | The callback to determine the error group name based on attribute data. |
Examples
Group errors by error class name:
Func<IReadOnlyDictionary<string, object>, string> errorGroupCallback = (attributes) => { string errorGroupName = string.Empty; if (attributes.TryGetValue("error.class", out var errorClass)) { if (errorClass.ToString() == "System.ArgumentOutOfRangeException" || errorClass.ToString() == "System.ArgumentNullException") { errorGroupName = "ArgumentErrors"; } else { errorGroupName = "OtherErrors"; } } return errorGroupName;};
NewRelic.Api.Agent.NewRelic.SetErrorGroupCallback(errorGroupCallback);
Group errors by transaction name:
Func<IReadOnlyDictionary<string, object>, string> errorGroupCallback = (attributes) => { string errorGroupName = string.Empty; if (attributes.TryGetValue("transactionName", out var transactionName)) { if (transactionName.ToString().IndexOf("WebTransaction/MVC/Home") != -1) { errorGroupName = "HomeControllerErrors"; } else { errorGroupName = "OtherControllerErrors"; } } return errorGroupName;};
NewRelic.Api.Agent.NewRelic.SetErrorGroupCallback(errorGroupCallback);
Syntax
NewRelic.Api.Agent.NewRelic.SetTransactionName(string $category, string $name)
Sets the name of the current transaction.
Requirements
- Compatible with all agent versions.
- Must be called inside a transaction.
Description
Sets the name of the current transaction. Before you use this call, ensure you understand the implications of metric grouping issues.
If you use this call multiple times within the same transaction, each call overwrites the previous call and the last call sets the name.
Important
Do not use brackets [suffix]
at the end of your transaction name. New Relic automatically strips brackets from the name. Instead, use parentheses (suffix)
or other symbols if needed.
Unique values like URLs, page titles, hex values, session IDs, and uniquely identifiable values should not be used in naming your transactions. Instead, add that data to the transaction as a custom parameter with the AddCustomAttribute()
call.
Important
Do not create more than 1000 unique transaction names (for example, avoid naming by URL if possible). This will make your charts less useful, and you may run into limits New Relic sets on the number of unique transaction names per account. It also can slow down the performance of your application.
Parameters
Parameter | Description |
---|---|
string | Required. The category of this transaction, which you can use to distinguish different types of transactions. Defaults to |
string | Required. The name of the transaction. Only the first 255 characters are retained. |
Examples
NewRelic.Api.Agent.NewRelic.SetTransactionName("Other", "MyTransaction");
Syntax
NewRelic.Api.Agent.NewRelic.SetTransactionUri(Uri $uri)
Sets the URI of the current transaction.
Requirements
- Must be called inside a transaction.
- Agent version 6.16 or higher.
Important
This method only works when used within a transaction created using the Transaction
attribute with the Web
property set to true
. (See Custom instrumentation via attributes.) It provides support for custom web-based frameworks that the agent does not automatically support.
Description
Sets the URI of the current transaction. The URI appears in the request.uri
attribute of transaction traces and transaction events, and it also can affect transaction naming.
If you use this call multiple times within the same transaction, each call overwrites the previous call. The last call sets the URI.
Note: as of agent version 8.18, the request.uri
attribute's value is set to the value of the Uri.AbsolutePath
property of the System.Uri
object passed to the API.
Parameters
Parameter | Description |
---|---|
Uri | The URI of this transaction. |
Examples
var uri = new System.Uri("https://www.mydomain.com/path");NewRelic.Api.Agent.NewRelic.SetTransactionUri(uri);
Syntax
NewRelic.Api.Agent.NewRelic.SetUserParameters(string $user_value, string $account_value, string $product_value)
Create user-related custom attributes. AddCustomAttribute
is more flexible.
Requirements
- Compatible with all agent versions.
- Must be called inside a transaction.
Description
Tip
This call only allows you to assign values to pre-existing keys. For a more flexible method to create key/value pairs, use AddCustomAttribute()
.
Define user-related custom attributesto associate with a browser page view (user name, account name, and product name). The values are automatically associated with pre-existing keys (user
, account
, and product
), then attached to the parent APM transaction. You can also attach (or "forward") these attributes to browser PageView events.
Parameters
Parameter | Description |
---|---|
string | Required (can be null). Specify a name or username to associate with this page view. This value is assigned to the |
string | Required (can be null). Specify the name of a user account to associate with this page view. This value is assigned to the |
string | Required (can be null). Specify the name of a product to associate with this page view. This value is assigned to the |
Examples
Record three user attributes
NewRelic.Api.Agent.NewRelic.SetUserParameters("MyUserName", "MyAccountName", "MyProductName");
Record two user attributes and one empty attribute
NewRelic.Api.Agent.NewRelic.SetUserParameters("MyUserName", "", "MyProductName");
Syntax
NewRelic.Api.Agent.NewRelic.StartAgent()
Start the agent if it hasn't already started. Usually unnecessary.
Requirements
- Compatible with all agent versions.
- Compatible with all app types.
Description
Starts the agent if it hasn't already been started. This call is usually unnecessary, since the agent starts automatically when it hits an instrumented method unless you disable autoStart
. If you use SetApplicationName()
, ensure you set the app name before you start the agent.
Tip
This method starts the agent asynchronously (meaning it won't block app startup) unless you enable syncStartup
or sendDataOnExit
.
Examples
NewRelic.Api.Agent.NewRelic.StartAgent();
Syntax
NewRelic.Api.Agent.TraceMetadata;
Returns properties in the current execution environment used to support tracing.
Requirements
- Agent version 8.19 or higher.
- Compatible with all app types.
- Distributed tracing must be enabled to get meaningful values.
Description
Provides access to the following properties:
Properties
Name | Description |
---|---|
| Returns a string representing the currently executing trace. If the trace ID is not available, or distributed tracing is disabled, the value will be |
| Returns a string representing the currently executing span. If the span ID is not available, or distributed tracing is disabled, the value will be |
| Returns |
Examples
IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();ITraceMetadata traceMetadata = agent.TraceMetadata;string traceId = traceMetadata.TraceId;string spanId = traceMetadata.SpanId;bool isSampled = traceMetadata.IsSampled;