Home

Awesome

<a href="https://opensource.newrelic.com/oss-category/#community-plus"><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.com/newrelic/opensource-website/raw/main/src/images/categories/dark/Community_Plus.png"><source media="(prefers-color-scheme: light)" srcset="https://github.com/newrelic/opensource-website/raw/main/src/images/categories/Community_Plus.png"><img alt="New Relic Open Source community plus project banner." src="https://github.com/newrelic/opensource-website/raw/main/src/images/categories/Community_Plus.png"></picture></a>

nuget

New Relic MAUI Plugin

This plugin allows you to instrument .NET MAUI mobile apps with help of native New Relic Android and iOS Bindings. The New Relic SDKs collect crashes, network traffic, and other information for hybrid apps using native components.

Features

Current Support:

This project targets .NET MAUI mobile apps and supports .NET MAUI minimum supported platforms:

Installation

Install NewRelic plugin into your MAUI project by adding the NuGet Package NewRelic.MAUI.Plugin.

Open your solution, select the project you want to add NewRelic package to and open its context menu. Unfold "Add" and click "Add NuGet packages...".

MAUI Setup

  1. Open your MauiProgram.cs and add the following code to launch NewRelic Plugin (don't forget to put proper application tokens):
using NewRelic.MAUI.Plugin;
...

    public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.ConfigureFonts(fonts =>
			{
				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
				fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
			});

        builder.ConfigureLifecycleEvents(AppLifecycle => {
        #if ANDROID
            AppLifecycle.AddAndroid(android => android
               .OnCreate((activity, savedInstanceState) => StartNewRelic()));
        #endif
        #if IOS

             AppLifecycle.AddiOS(iOS => iOS.WillFinishLaunching((_,__) => {
                StartNewRelic();
                return false;
            }));
        #endif
        });
		return builder.Build();
	}

    private static void StartNewRelic()
    {
       
      CrossNewRelic.Current.HandleUncaughtException();

      // Set optional agent configuration
      // Options are: crashReportingEnabled, loggingEnabled, logLevel, collectorAddress, crashCollectorAddress,analyticsEventEnabled, networkErrorRequestEnabled, networkRequestEnabled, interactionTracingEnabled,webViewInstrumentation, fedRampEnabled,offlineStorageEnabled,newEventSystemEnabled,backgroundReportingEnabled
      // AgentStartConfiguration agentConfig = new AgentStartConfiguration(crashReportingEnabled:false);


      if (DeviceInfo.Current.Platform == DevicePlatform.Android) 
      {
        CrossNewRelic.Current.Start("<APP-TOKEN-HERE>");
        // Start with optional agent configuration 
        // CrossNewRelic.Current.Start("<APP-TOKEN-HERE", agentConfig);
      } else if (DeviceInfo.Current.Platform == DevicePlatform.iOS)
      {
        CrossNewRelic.Current.Start("<APP-TOKEN-HERE>");
        // Start with optional agent configuration 
        // CrossNewRelic.Current.Start("<APP-TOKEN-HERE", agentConfig);
      }
    }

Android Setup

  1. Open Platforms/Android/AndroidManifest.xml for your Android App and add the following permissions:
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />

Screen Tracking Events

The .NET MAUI mobile plugin allows you to track navigation events within the .NET MAUI Shell. In order to do so, you only need to call:

    public App()
	{
		InitializeComponent();

		MainPage = new AppShell();
		CrossNewRelic.Current.TrackShellNavigatedEvents();

    }

It is recommended to call this method along when starting the agent. These events will only be recorded after navigation is complete. You can find this data through the data explorer in MobileBreadcrumb under the name ShellNavigated or by query:

    SELECT * FROM MobileBreadcrumb WHERE name = 'ShellNavigated' SINCE 24 HOURS AGO

The breadcrumb will contain three attributes:

Usage

See the examples below, and for more detail, see New Relic iOS SDK doc or Android SDK .

CrashNow(string message = "") : void;

Throws a demo run-time exception on Android/iOS to test New Relic crash reporting.

    CrossNewRelic.Current.CrashNow();

CurrentSessionId() : string;

Returns ID for the current session.

    string sessionId = CrossNewRelic.Current.CurrentSessionId();

StartInteraction(string interactionName): string;

Track a method as an interaction.

EndInteraction(string interactionId): void;

End an interaction (Required). This uses the string ID for the interaction you want to end. This string is returned when you use startInteraction().

    HttpClient myClient = new HttpClient(CrossNewRelic.Current.GetHttpMessageHandler());
    
    string interactionId = CrossNewRelic.Current.StartInteraction("Getting data from service");

    var response = await myClient.GetAsync(new Uri("https://jsonplaceholder.typicode.com/todos/1"));
    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
    } else
    {
        Console.WriteLine("Unsuccessful response code");
    }

    CrossNewRelic.Current.EndInteraction(interactionId);

NoticeHttpTransaction(string url, string httpMethod, int statusCode, long startTime,long endTime, long bytesSent, long bytesReceived, string responseBody): void;

Tracks network requests manually. You can use this method to record HTTP transactions, with an option to also send a response body.

    CrossNewRelic.Current.NoticeHttpTransaction(
      "https://newrelic.com",
      "GET",
      200,
      DateTimeOffset.Now.ToUnixTimeMilliseconds(),
      DateTimeOffset.Now.ToUnixTimeMilliseconds() + 100,
      0,
      1000,
      ""
    );

NoticeNetworkFailure(string url, string httpMethod, int statusCode, long startTime,long endTime, long bytesSent, long bytesReceived, string responseBody): void;

Records network failures. If a network request fails, use this method to record details about the failure.

    CrossNewRelic.Current.NoticeNetworkFailure(
      "https://fakewebsite.com",
      "GET",
      DateTimeOffset.Now.ToUnixTimeMilliseconds(),
      DateTimeOffset.Now.ToUnixTimeMilliseconds() + 100,
      NetworkFailure.Unknown
    );

RecordBreadcrumb(string name, Dictionary<string, object> attributes): bool;

This call creates and records a MobileBreadcrumb event, which can be queried with NRQL and in the crash event trail.

    CrossNewRelic.Current.RecordBreadcrumb("MAUIExampleBreadcrumb", new Dictionary<string, object>()
        {
            {"BreadNumValue", 12.3 },
            {"BreadStrValue", "MAUIBread" },
            {"BreadBoolValue", true }
        }
    );

RecordCustomEvent(string eventType, string eventName, Dictionary<string, object> attributes): bool;

Creates and records a custom event for use in New Relic Insights.

    CrossNewRelic.Current.RecordCustomEvent("MAUICustomEvent", "MAUICustomEventCategory", new Dictionary<string, object>()
        {
            {"BreadNumValue", 12.3 },
            {"BreadStrValue", "MAUIBread" },
            {"BreadBoolValue", true }
        }
    );

RecordMetric(string name, string category) : void;

RecordMetric(string name, string category, double value) : void;

Record custom metrics (arbitrary numerical data).

    CrossNewRelic.Current.RecordMetric("Agent start", "Lifecycle");
    CrossNewRelic.Current.RecordMetric("Login Auth Metric", "Network", 78.9);

SetAttribute(string name, string value) : bool;

SetAttribute(string name, double value) : bool;

SetAttribute(string name, bool value) : bool;

Creates a session-level attribute shared by multiple mobile event types. Overwrites its previous value and type each time it is called.

    CrossNewRelic.Current.SetAttribute("MAUIBoolAttr", false);
    CrossNewRelic.Current.SetAttribute("MAUIStrAttr", "Cat");
    CrossNewRelic.Current.SetAttribute("MAUINumAttr", 13.5);

IncrementAttribute(string name, float value = 1) : bool;

Increments the count of an attriubte. Overwrites its previous value and type each time it is called.

    // Increment by 1
    CrossNewRelic.Current.IncrementAttribute("MAUINumAttr");
    // Increment by value
    CrossNewRelic.Current.IncrementAttribute("MAUINumAttr", 12.3);

RemoveAttribute(string name) : bool;

Removes an attribute.

    CrossNewRelic.Current.RemoveAttribute("MAUINumAttr");

RemoveAllAttributes() : bool;

Removes all attributes from the session.

    CrossNewRelic.Current.RemoveAllAttributes();

SetMaxEventBufferTime(int maxBufferTimeInSec) void;

Sets the event harvest cycle length.

    CrossNewRelic.Current.SetMaxEventBufferTime(200);

SetMaxEventPoolSize(int maxPoolSize): void;

Sets the maximum size of the event pool.

    CrossNewRelic.Current.SetMaxEventPoolSize(1500);

SetUserId(string userId): bool;

Set a custom user identifier value to associate user sessions with analytics events and attributes.

    CrossNewRelic.Current.SetUserId("User123");

GetHttpMessageHandler() : HttpMessageHandler;

Provides a HttpMessageHandler to instrument http requests through HttpClient.

    HttpClient myClient = new HttpClient(CrossNewRelic.Current.GetHttpMessageHandler());

    var response = await myClient.GetAsync(new Uri("https://jsonplaceholder.typicode.com/todos/1"));
    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
    } else
    {
        Console.WriteLine("Http request failed");
    }

AnalyticsEventEnabled(bool enabled) : void

FOR ANDROID ONLY. Enable or disable collection of event data.

    CrossNewRelic.Current.AnalyticsEventEnabled(true);

NetworkRequestEnabled(bool enabled) : void

Enable or disable reporting successful HTTP requests to the MobileRequest event type.

    CrossNewRelic.Current.NetworkRequestEnabled(true);

NetworkErrorRequestEnabled(bool enabled) : void

Enable or disable reporting network and HTTP request errors to the MobileRequestError event type.

    CrossNewRelic.Current.NetworkErrorRequestEnabled(true);

HttpResponseBodyCaptureEnabled(bool enabled) : void

Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.

    CrossNewRelic.Current.HttpResponseBodyCaptureEnabled(true);

Shutdown() : void

Shut down the agent within the current application lifecycle during runtime.

    CrossNewRelic.Current.Shutdown();

SetMaxOfflineStorageSize(int megabytes) : void

Sets the maximum size of total data that can be stored for offline storage.By default, mobile monitoring can collect a maximum of 100 megaBytes of offline storage. When a data payload fails to send because the device doesn't have an internet connection, it can be stored in the file system until an internet connection has been made. After a typical harvest payload has been successfully sent, all offline data is sent to New Relic and cleared from storage.

    CrossNewRelic.Current.SetMaxOfflineStorageSize(200);

LogInfo(String message) : void

Logs an informational message to the New Relic log.

    CrossNewRelic.Current.LogInfo("This is an informational message");

LogError(String message) : void

Logs an error message to the New Relic log.

    CrossNewRelic.Current.LogError("This is an error message");

LogVerbose(String message) : void

Logs a verbose message to the New Relic log.

    CrossNewRelic.Current.LogVerbose("This is a verbose message");

LogWarning(String message) : void

Logs a warning message to the New Relic log.

    CrossNewRelic.Current.LogWarning("This is a warning message");

LogDebug(String message) : void

Logs a debug message to the New Relic log.

    CrossNewRelic.Current.LogDebug("This is a debug message");

Log(LogLevel level, String message) : void

Logs a message to the New Relic log with a specified log level.

    CrossNewRelic.Current.Log(LogLevel.Info, "This is an informational message");

LogAttributes(Dictionary<string, object> attributes) : void

Logs a message with attributes to the New Relic log.

    CrossNewRelic.Current.LogAttributes(new Dictionary<string, object>()
        {
            {"BreadNumValue", 12.3 },
            {"BreadStrValue", "MAUIBread" },
            {"BreadBoolValue", true },
            {"message", "This is a message with attributes" }
        }
    );

Error reporting

This plugin provides a handler to record unhandled exceptions to New Relic. It is recommended to initialize the handler prior to starting the agent.

HandleUncaughtException(bool shouldThrowFormattedException = true) : void;

    CrossNewRelic.Current.HandleUncaughtException();
    if (DeviceInfo.Current.Platform == DevicePlatform.Android) 
    {
        CrossNewRelic.Current.Start("<APP-TOKEN-HERE>");
    } else if (DeviceInfo.Current.Platform == DevicePlatform.iOS)
    {
        CrossNewRelic.Current.Start("<APP-TOKEN-HERE>");
    }

This plugin also provides a method to manually record any handled exceptions as well:

RecordException(System.Exception exception) : void;

    try {
      some_code_that_throws_error();
    } catch (Exception ex) {
      CrossNewRelic.Current.RecordException(ex);
    }

Troubleshooting

Support

New Relic hosts and moderates an online forum where customers, users, maintainers, contributors, and New Relic employees can discuss and collaborate:

forum.newrelic.com.

Contribute

We encourage your contributions to improve [project name]! Keep in mind that when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.

If you have any questions, or to execute our corporate CLA (which is required if your contribution is on behalf of a company), drop us an email at opensource@newrelic.com.

A note about vulnerabilities

As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.

If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through HackerOne.

If you would like to contribute to this project, review these guidelines.

To all contributors, we thank you! Without your contribution, this project would not be what it is today.

License

Except as described below, the newrelic-maui-plugin is licensed under the Apache 2.0 License.

The [New Relic XCFramework agent] (/docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile-ios/get-started/introduction-new-relic-mobile-ios/) is licensed under the [New Relic Agent Software Notice] (/docs.newrelic.com/docs/licenses/license-information/distributed-licenses/new-relic-agent-software-notice/).

The [New Relic Android agent] (github.com/newrelic/newrelic-android-agent) is licensed under the Apache 2.0.

The newrelic-maui-plugin may use source code from third-party libraries. When used, these libraries will be outlined in THIRD_PARTY_NOTICES.md.