NewRelic.MAUI.Plugin 1.0.0

Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package NewRelic.MAUI.Plugin --version 1.0.0                
NuGet\Install-Package NewRelic.MAUI.Plugin -Version 1.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NewRelic.MAUI.Plugin" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add NewRelic.MAUI.Plugin --version 1.0.0                
#r "nuget: NewRelic.MAUI.Plugin, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install NewRelic.MAUI.Plugin as a Cake Addin
#addin nuget:?package=NewRelic.MAUI.Plugin&version=1.0.0

// Install NewRelic.MAUI.Plugin as a Cake Tool
#tool nuget:?package=NewRelic.MAUI.Plugin&version=1.0.0                

<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

  • Capture Android and iOS Crashes
  • Network Request tracking
  • Distributed Tracing
  • Pass user information to New Relic to track user sessions
  • Screen Tracking
  • Capture Offline Events and Exception
  • Capture Background Events when app is in background

Current Support:

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

  • Android 7.0 (API 24) or higher
  • iOS 11 or higher, using the latest release of Xcode
  • Depends on New Relic iOS/XCFramework and Android agents

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:

  • Current: The URI of the current page.
  • Source: The type of navigation that occurred.
  • Previous: The URI of the previous page. Will not exist if previous page was null.

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);

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

  • No Http data appears:

    • To instrument http data, make sure to use the HttpMessageHandler in HttpClient.

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.

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-android33.0 is compatible.  net7.0-ios was computed.  net7.0-ios16.1 is compatible.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.4 2,270 10/11/2024
1.1.3 3,529 9/27/2024
1.1.2 199 9/23/2024
1.1.1 2,108 8/22/2024
1.1.0 2,945 7/18/2024
1.0.0 3,312 6/3/2024
0.0.9 5,783 5/7/2024
0.0.8 177 5/7/2024
0.0.7 4,618 3/22/2024
0.0.6 1,000 3/6/2024
0.0.5 4,594 2/22/2024
0.0.4 1,493 12/14/2023
0.0.3 1,481 10/5/2023
0.0.2 1,335 7/17/2023
0.0.1 672 6/8/2023