newrelic/newrelic-flutter-agent
New Relic agent SDK for Flutter hybrid mobile apps
baixar do githubNew Relic Flutter Agent
This agent allows you to instrument Flutter apps with help of native New Relic Android and iOS
agents. The New Relic SDKs collect crashes, network traffic, and other information for hybrid apps
using native components.
Features
- Capture Dart errors
- Network Request tracking
- Distributed Tracing
- Future errors tracking
- Capture interactions and the sequence in which they were created
- Pass user information to New Relic to track user sessions
- Screen tracking via NavigationObserver
- Capture print and debug print statement as CustomEvents
- Capture Offline Events and Exception
Current Support:
- Android API 24+
- iOS 10
- Depends on New Relic iOS/XCFramework and Android agents
Requirements
- Flutter “>= 2.5.0”
- Dart “>=2.16.2 <4.0.0”
- IOS native requirements
- Android native requirements
Installation
Install NewRelic plugin into your dart project by adding it to dependecies in your pubspec.yaml
dependencies:
newrelic_mobile: 1.0.8
Flutter Setup
- Now open your
main.dart
and add the following code to launch NewRelic (don’t forget to put proper
application tokens):
import 'package:newrelic_mobile/newrelic_mobile.dart';
var appToken = "";
if (Platform.isAndroid) {
appToken = "<android app token>";
} else if (Platform.isIOS) {
appToken = "<ios app token>";
}
Config config =
Config(accessToken: appToken,
//Android Specific
// Optional:Enable or disable collection of event data.
analyticsEventEnabled: true,
// Optional:Enable or disable reporting network and HTTP request errors to the MobileRequestError event type.
networkErrorRequestEnabled: true,
// Optional:Enable or disable reporting successful HTTP requests to the MobileRequest event type.
networkRequestEnabled: true,
// Optional:Enable or disable crash reporting.
crashReportingEnabled: true,
// Optional:Enable or disable interaction tracing. Trace instrumentation still occurs, but no traces are harvested. This will disable default and custom interactions.
interactionTracingEnabled: true,
// Optional:Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.
httpResponseBodyCaptureEnabled: true,
// Optional: Enable or disable agent logging.
loggingEnabled: true,
//iOS Specific
// Optional:Enable/Disable automatic instrumentation of WebViews
webViewInstrumentation: true,
//Optional: Enable or Disable Print Statements as Analytics Events
printStatementAsEventsEnabled : true,
// Optional:Enable/Disable automatic instrumentation of Http Request
httpInstrumentationEnabled:true,
// Optional : Enable or disable reporting data using different endpoints for US government clients
fedRampEnabled: false ,
// Optional: Enable or disable offline data storage when no internet connection is available.
offlineStorageEnabled:true
);
NewrelicMobile.instance.start(config, () {
runApp(MyApp());
});
class MyApp extends StatelessWidget {
....
- Alternatively, you can manually set up error tracking and resource tracking. Because NewRelic Mobile Start calls WidgetsFlutterBinding.ensureInitialized, if you are not using NewRelic Mobile Start, you need to call this method prior to calling NewrelicMobile.instance.startAgent.
if (Platform.isAndroid) {
appToken = AppConfig.androidToken;
} else if (Platform.isIOS) {
appToken = AppConfig.iOSToken;
}
Config config = Config(
accessToken: appToken,
analyticsEventEnabled: true,
networkErrorRequestEnabled: true,
networkRequestEnabled: true,
crashReportingEnabled: true,
interactionTracingEnabled: true,
httpResponseBodyCaptureEnabled: true,
loggingEnabled: true,
webViewInstrumentation: true,
printStatementAsEventsEnabled: true,
httpInstrumentationEnabled:true);
// NewrelicMobile.instance.start(config, () {
// runApp(MyApp());
// });
runZonedGuarded(() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = NewrelicMobile.onError;
await NewrelicMobile.instance.startAgent(config);
runApp(MyApp());
}, (Object error, StackTrace stackTrace) {
NewrelicMobile.instance.recordError(error, stackTrace);
});
AppToken is platform-specific. You need to generate the seprate token for Android and iOS apps.
Screen Tracking Events
In order to track navigation events you have to add the NewRelicNavigationObserver to your
MaterialApp, WidgetsApp or CupertinoApp.
You should provide a name to route settings: RouteSettings(name: ‘Your Route Name’). The root route
name / will be replaced by root “/” for clarity’s sake.
import 'package:newrelic_mobile/newrelic_navigation_observer.dart';
//....
MaterialApp(
navigatorObservers: [
NewRelicNavigationObserver(),
],
// other parameters
)
GoRouter Instrumentation
When using the go_router[https://pub.dev/packages/go_router] library, the automatic routing instrumentation can be enabled by adding an instance of NewRelicNavigationObserver to your application’s GoRouter.observers:
//....
import 'package:go_router/go_router.dart';
import 'package:newrelic_mobile/newrelic_navigation_observer.dart';
final router = GoRouter(
routes: ...,
observers: [NewRelicNavigationObserver()],
);
Android Setup
- Add the following changes to android/build.gradle:
buildscript {
...
repositories {
...
mavenCentral()
}
dependencies {
...
classpath "com.newrelic.agent.android:agent-gradle-plugin:7.2.0"
}
}
- Apply the newrelic plugin to the top of the android/app/build.gradle file::
apply plugin: "com.android.application"
apply plugin: 'newrelic' // <-- add this
- Make sure your app requests INTERNET and ACCESS_NETWORK_STATE permissions by adding these lines
to yourAndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage
See the examples below, and for more detail,
see New Relic IOS SDK doc
or Android SDK
.
startInteraction(String actionName) Future;
Track a method as an interaction.
InteractionId
is string.
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().
var id = await NewrelicMobile.instance.startInteraction("Getting Data from Service");
try {
var dio = Dio();
var response = await dio.get(
'https://reqres.in/api/users?delay=15');
print(response);
NewrelicMobile.instance.endInteraction(id);
Timeline.finishSync();
} catch (e) {
print(e);
}
[setAttribute] (https://docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile-ios/ios-sdk-api)(String name, dynamic value) : void;
Creates a session-level attribute shared by multiple mobile event types. Overwrites its previous value and type each time it is called.
NewrelicMobile.instance.setAttribute('RNCustomAttrNumber', 37);
setUserId(String userId): void;
Set a custom user identifier value to associate user sessions with analytics events and attributes.
NewrelicMobile.instance.setUserId("RN12934");
recordBreadcrumb(String name,{Map<String, dynamic>? eventAttributes}): void;
Track app activity/screen that may be helpful for troubleshooting crashes.
NewrelicMobile.instance.recordBreadcrumb("Button Got Pressed on Screen 3"),
recordCustomEvent(String eventType,{String eventName = “”, Map<String, dynamic>? eventAttributes}): void;
Creates and records a custom event for use in New Relic Insights.
NewrelicMobile.instance.recordCustomEvent("Major",eventName: "User Purchase",eventAttributes: {"item1":"Clothes","price":34.00}),
child: const Text('Record Custom Event'),
setMaxEventBufferTime(int maxBufferTimeInSec) void;
Sets the event harvest cycle length.
NewrelicMobile.instance.setMaxEventBufferTime(200);
setMaxEventPoolSize(int maxSize): void;
Sets the maximum size of the event pool.
NewrelicMobile.instance.setMaxEventPoolSize(10000);
noticeHttpTransaction(String url,String httpMethod,int statusCode,int startTime,int endTime,int bytesSent,int bytesReceived,Map<String, dynamic>? traceData,{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.
NewrelicMobile.instance.noticeHttpTransaction("https://cb6b02be-a319-4de5-a3b1-361de2564493.mock.pstmn.io/searchpage", "GET",200, 1000, 2000,100,300,null,responseBody: "This is Test Payload");
noticeNetworkFailure(String url,String httpMethod,int startTime,int endTime,NetworkFailure errorCode): void;
Records network failures. If a network request fails, use this method to record details about the failures. In most cases, place this call inside exception handlers, such as catch blocks. Supported failures are: Unknown, BadURL, TimedOut, CannotConnectToHost, DNSLookupFailed, BadServerResponse, SecureConnectionFailed.
NewrelicMobile.instance.noticeNetworkFailure("https://cb6b02be-a319-4de5-a3b1-361de2564493.mock.pstmn.io/searchpage", "GET", 1000, 2000,'Test Network Failure', NetworkFailure.dnsLookupFailed);
recordMetric(name: string, category: string, value?: number, countUnit?: string, valueUnit?: string): void;
Records custom metrics (arbitrary numerical data), where countUnit is the measurement unit of the metric count and valueUnit is the measurement unit for the metric value. If using countUnit or valueUnit, then all of value, countUnit, and valueUnit must all be set.
NewrelicMobile.instance.recordMetric("testMetric", "Test Champ",value: 12.0);
NewrelicMobile.instance.recordMetric("testMetric1", "TestChamp12",value: 10,valueUnit: MetricUnit.BYTES,countUnit: MetricUnit.PERCENT);
currentSessionId(): Promise;
Returns the current session ID. This method is useful for consolidating monitoring of app data (not just New Relic data) based on a single session definition and identifier.
var sessionId = await NewrelicMobile.instance.currentSessionId();
setAttribute(name: string, value: boolean | number | string): void;
Creates a session-level attribute shared by multiple mobile event types. Overwrites its previous value and type each time it is called.
NewrelicMobile.instance.setAttribute("FlutterCustomAttrNumber",value :5.0);
removeAttribute(name: string, value: boolean | number | string): void;
This method removes the attribute specified by the name string…
NewrelicMobile.instance.removeAttribute("FlutterCustomAttrNumber");
incrementAttribute(name: string, value?: number): void;
Increments the count of an attribute with a specified name. Overwrites its previous value and type each time it is called. If the attribute does not exists, it creates a new attribute. If no value is given, it increments the value by 1.
NewrelicMobile.instance.incrementAttribute("FlutterCustomAttrNumber");
NewrelicMobile.instance.incrementAttribute("FlutterCustomAttrNumber",value :5.0);
shutdown() : void;
Shut down the agent within the current application lifecycle during runtime.
NewrelicMobile.instance.shutdown();
shutdown() : void;
This API allows you to add any header field strings to a list that gets recorded as attributes with networking request events. After header fields have been added using this function, if the headers are in a network call they will be included in networking events in NR1.
NewrelicMobile.instance.addHTTPHeadersTrackingFor(["Car","Music"]);
Manual Error reporting
You can register non fatal exceptions using the following method with Custom Attributes:
try {
some_code_that_throws_error();
} catch (ex) {
NewrelicMobile.instance
.recordError(error, StackTrace.current, attributes: attributes);
}
Troubleshoot
No Http data appears:
Problem
After installing the Flutter agent and waiting at least 5 minutes, no http data appears in New Relic UI.
Solution
If no http data appears after you wait at least five minutes, check you are not overriding HttpOverrides.global inside your flutter app.
Uploading dSYM files
Our iOS agent includes a Swift script intended to be run from a build script in your target’s build phases in XCode. The script automatically uploads dSYM files in the background (or converts your dSYM to the New Relic map file format), and then performs a background upload of the files needed for crash symbolication to New Relic.
To invoke this script during an XCode build:
- Copy the dsym-upload-tools folder from this repository: https://github.com/newrelic/newrelic-ios-agent-spm, to your projects SRCROOT folder first.
- In Xcode, select your project in the navigator, then click on the application target.
- Select the Build Phases tab in the settings editor.
- Click the + icon above Target Dependencies and choose New Run Script Build Phase. Ensure the new build script is the very last build script.
- Add the following lines of code to the new phase and replace
APP_TOKEN
with your iOS application token.- If there is a checkbox below Run script that says “Run script: Based on Dependency analysis” please make sure it is not checked.
Flutter agent 1.0.2 or higher
With the ios agent 7.4.6 release, the XCFramework no longer includes the dsym-upload-tools. You can find the dsym-upload-tools in the dsym-upload-tools folder of the https://github.com/newrelic/newrelic-ios-agent-spm Swift Package Manager repository. Please copy the dsym-upload-tools directory into your application source code directory by copying the XCFramework into your project or using Cocoapods if you’re integrating the New Relic iOS Agent. Use the run script below in your Xcode build phases to perform symbol upload steps during app builds in Xcode.
ARTIFACT_DIR="${BUILD_DIR%Build/*}"
SCRIPT=`/usr/bin/find "${SRCROOT}" "${ARTIFACT_DIR}" -type f -name run-symbol-tool | head -n 1`
/bin/sh "${SCRIPT}" "APP_TOKEN"
Note: The automatic script requires bitcode to be disabled. You should clean and rebuild your app after adding the script.
Missing dSYMs
The automatic script will create an upload_dsym_results.log
file in your project’s iOS directory, which contains information about any failures that occur during symbol upload.
If dSYM files are missing, you may need to check Xcode build settings to ensure the file is being generated. Frameworks which are built locally have separate build settings and may need to be updated as well.
Build settings:
Debug Information Format : Dwarf with dSYM File
Deployment Postprocessing: Yes
Strip Linked Product: Yes
Strip Debug Symbols During Copy : Yes
Configure app launch times
To measure app launch time, you can refer to the following documentation for both Android and iOS platforms.
Support
New Relic hosts and moderates an online forum where customers, users, maintainers, contributors, and New Relic employees can discuss and collaborate:
Contribute
We encourage your contributions to improve newrelic-flutter-agent! 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.
License
newrelic-flutter-agent is licensed under the Apache 2.0
License.
newrelic-flutter-agent also uses source code from third-party libraries. Full details on which libraries are used and the terms under which they are licensed can be found in the third-party notices document.
![](/images/banner-woo.jpg)
recomendações de excelentes projetos relacionados a newrelic/newrelic-flutter-agent para download
AppFlowy
47859
AppFlowy is an open-source alternative to Notion. You are in charge of your data and customizations. Built with Flutter and Rust.
localsend
33797
An open-source cross-platform alternative to AirDrop
spotube
23772
🎧 Open source Spotify client that doesn't require Premium nor uses Electron! Available for both desktop & mobile!
revanced-manager
15035
💊 Application to use ReVanced on Android
gsy_github_app_flutter
14559
Flutter 超完整的开源项目,功能丰富,适合学习和日常使用。GSYGithubApp系列的优势:我们目前已经拥有Flutter、Weex、ReactNative、kotlin 四个版本。 功能齐全,项目框架内技术涉及面广,完成度高,持续维护,配套文章,适合全面学习,对比参考。跨平台的开源Github客户端App,更好的体验,更丰富的功能,旨在更好的日常管理和维护个人Github,提供更好更方便的驾车体验Σ( ̄。 ̄ノ)ノ。同款Weex版本 : https://github.com/CarGuo/GSYGithubAppWeex 、同款React Native版本 : https://github.com/CarGuo/GSYGithubApp 、原生 kotlin 版本 https://github.com/CarGuo/GSYGithubAppKotlin
dio
12249
A powerful HTTP client for Dart and Flutter, which supports global settings, Interceptors, FormData, aborting and canceling a request, files uploading and downloading, requests timeout, custom adapters, etc.
gopeed
11832
A modern download manager that supports all platforms. Built with Golang and Flutter.
bloc
11441
A predictable state management library that helps implement the BLoC design pattern
getx
9899
Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with Get.
flame
8846
A Flutter based game engine.
flutter_deer
7595
🦌 Flutter 练习项目(包括集成测试、可访问性测试)。内含完整UI设计图,更贴近真实项目的练习。Flutter practice project (including integration testing and accessibility testing). Contains complete UI design drawings for a more realistic practice project.
fish-redux
7343
An assembled flutter application framework.
hiddify-next
7232
Multi-platform auto-proxy client, supporting Sing-box, X-ray, TUIC, Hysteria, Reality, Trojan, SSH etc. It’s an open-source, secure and ad-free.
ente
6686
Fully open source, End to End Encrypted alternative to Google Photos and Apple Photos
fl_chart
6451
FL Chart is a highly customizable Flutter chart library that supports Line Chart, Bar Chart, Pie Chart, Scatter Chart, and Radar Chart.
pixez-flutter
6360
一个支持免代理直连及查看动图的第三方Pixiv flutter客户端
Flutter-Responsive-Admin-Panel-or-Dashboard
6355
Responsive Admin Panel or Dashboard using Flutter
aidea
6021
AIdea 是一款支持 GPT 以及国产大语言模型通义千问、文心一言等,支持 Stable Diffusion 文生图、图生图、 SDXL1.0、超分辨率、图片上色的全能型 APP。
riverpod
5828
A reactive caching and data-binding framework. Riverpod makes working with asynchronous code a breeze.
pikapika
5463
美观易用且无广告的漫画和游戏客户端,同时支持MacOS,Windows,Android,iOS。