This is the repository of the Mac SDK for Application Insights. Application Insights is a service that allows developers to keep their applications available, performing, and succeeding. The SDK enables you to send telemetry of various kinds (events, traces, exceptions, etc.) to the Application Insights service where your data can be visualized in the Azure Portal.
The SDK runs on devices with OS X 10.8 or higher.
- Release Notes
- Requirements
- Setup
- Advanced Setup
- Developer Mode
- Basic Usage
- Advanced Usage
- Automatic collection of lifecycle events
- Crash Reporting
- Set Custom Server Endpoint
- Documentation
- Contributing
- Contact
- This is the third pre-release
- It provides support for collecting telemetry and crash reports
- Fixes crashes when running on OS X 10.8
- Based on the iOS SDK Version 1.0-Beta.4
The SDK runs on devices with OS X 10.8 or higher.
We recommend integration of our binary into your Xcode project to setup Application Insights for your OS X app. For other ways to setup the SDK, see Advanced Setup.
Please see the "Getting an Application Insights Instrumentation Key" section of the wiki for more information on acquiring a key.
- Download the latest Application Insights for iOS framework which is provided as a zip-File.
- Unzip the file and you will see a folder called
ApplicationInsights
.
From our experience, 3rd-party libraries usually reside inside a subdirectory (let's call our subdirectory Vendor
), so if you don't have your project organized with a subdirectory for libraries, now would be a great start for it. To continue our example, create a folder called "Vendor" inside your project directory and move the unzipped ApplicationInsights
-folder into it.
- We recommend to use Xcode's group-feature to create a group for 3rd-party-libraries similar to the structure of our files on disk. For example, similar to the file structure in 3.1 above, our projects have a group called
Vendor
. - Make sure the
Project Navigator
is visible (⌘+1) - Drag & drop
ApplicationInsights.framework
from your window in theFinder
into your project in Xcode and move it to the desired location in theProject Navigator
(e.g. into the group calledVendor
) - A popup will appear. Select
Create groups for any added folders
and set the checkmark for your target. Then clickFinish
. - Select your project in the
Project Navigator
(⌘+1). - Select your app target.
- Select the tab
Build Phases
.- Click the
+
button at the top and chooseAdd Copy Files
. - Click the disclosure triangle next to the new build phase.
- Choose
Frameworks
from the Destination list. - Drag
ApplicationInsights.framework
from theProject Navigator
to the list in the new Copy Files phase.
- Click the
- Open the
Info.plist
of your app target and add a new field of type String. Name itMSAIInstrumentationKey
and set your Application Insights instrumentation key as its value.
Objective-C
-
Open your
AppDelegate.m
file. -
Add the following line at the top of the file below your own
import
statements:#import <ApplicationInsightsOSX/ApplicationInsights.h>
-
Search for the method
application:didFinishLaunchingWithOptions:
-
Add the following lines to setup and start the Application Insights SDK:
// Setup Application Insights SDK [[MSAIApplicationInsights sharedInstance] setup]; // Do some additional configuration if needed here ... [[MSAIApplicationInsights sharedInstance] start];
You can also use the following shortcuts:
[MSAIApplicationInsights setup]; [MSAIApplicationInsights start];
Swift
-
Open your
AppDelegate.swift
file. -
Add the following line at the top of the file below your own import statements:
import ApplicationInsightsOSX
-
Search for the method
func applicationDidFinishLaunching(_ aNotification: NSNotification)
-
Add the following lines to setup and start the Application Insights SDK:
MSAIApplicationInsights.sharedInstance().setup() MSAIApplicationInsights.sharedInstance().start()
You can also use the following shortcuts:
```swift
MSAIApplicationInsights.setup()
MSAIApplicationInsights.start()
```
Congratulation, now you're all set to use Application Insights! See Basic Usage on how to use Application Insights.
It is also possible to set the instrumentation key of your app in code. This will override the one you might have set in your Info.plist
. To set it in code, MSAIApplicationInsights provides an overloaded constructor:
[MSAIApplicationInsights setupWithInstrumentationKey:@"{YOUR-INSTRUMENTATIONKEY}"];
//Do additional configuration
[MSAIApplicationInsights start];
CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like ApplicationInsights in your projects. To learn how to setup CocoaPods for your project, visit the official CocoaPods website.
[NOTE]
When adding Application Insights to your podfile without specifying the version, pod install
will throw an error because using a pre-release version of a pod has to be specified explicitly.
As soon as Application Insights 1.0 is available, the version doesn't have to be specified in your podfile anymore.
Podfile
platform :osx, '10.8'
pod "ApplicationInsights-OSX", '1.0-beta.1'
The following points need to be considered to use the Application Insights SDK with OS X Extensions:
- Each extension is required to use the same values for version (
CFBundleShortVersionString
) and build number (CFBundleVersion
) as the main app uses. (This is required only if you are using the sameMSAIInstrumentationKey
for your app and extensions). - You need to make sure the SDK setup code is only invoked once. Since there is no
applicationDidFinishLaunching:
equivalent andviewDidLoad
can run multiple times, you need to use a setup like the following example:
@interface TodayViewController () <NCWidgetProviding>
@property (nonatomic, assign) BOOL didSetupApplicationInsightsSDK;
@end
@implementation TodayViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (!self.didSetupApplicationInsightsSDK) {
[MSAIApplicationInsights setup];
[MSAIApplicationInsights start];
self.didSetupApplicationInsightsSDK = YES;
}
}
###5.1 Batching of data
The developer mode is enabled automatically in case the debugger is attached. This will decrease the number of telemetry items sent in a batch (5 items) as well as the interval items when telemetry will be sent (3 seconds).
###5.2 Logging
We're all big fans of a clean debugging output without 3rd-party-SDKs messages piling up in the debugging view, right?! That's why Application Insights keeps log messages to a minimum (like critical errors) unless the developer specifically enables debug logging before starting the SDK:
[MSAIApplicationInsights setup]; //setup the SDK
[[MSAIApplicationInsights sharedInstance] setDebugLogEnabled:YES]; //enable debug logging
[MSAIApplicationInsights start]; //start using the SDK
[NOTE] The SDK is optimized to defer everything possible to a later time while making sure e.g. crashes on startup can also be caught and each module executes other code with a delay of some seconds. This ensures that applicationDidFinishLaunching:
will process as fast as possible and the SDK will not block the startup sequence resulting in a possible kill by the watchdog process.
After you have set up the SDK as described above, the MSAITelemetryManager
-instance is the central interface to track events, traces, metrics, page views or handled exceptions.
// Send an event with custom properties and measurements data
[MSAITelemetryManager trackEventWithName:@"Hello World event!"
properties:@{@"Test property 1":@"Some value",
@"Test property 2":@"Some other value"}
measurements:@{@"Test measurement 1":@(4.8),
@"Test measurement 2":@(15.16),
@"Test measurement 3":@(23.42)}];
// Send a message
[MSAITelemetryManager trackTraceWithMessage:@"Test message"];
// Manually send pageviews (note: this will also be done automatically)
[MSAITelemetryManager trackPageView:@"MyViewController"
duration:300
properties:@{@"Test measurement 1":@(4.8)}];
// Send custom metrics
[MSAITelemetryManager trackMetricWithName:@"Test metric" value:42.2];
// Track handled exceptions
NSArray *zeroItemArray = [NSArray new];
@try {
NSString *fooString = zeroItemArray[3];
} @catch(NSException *exception) {
[MSAITelemetryManager trackException:exception];
}
// Send an event with custom properties and measuremnts data
MSAITelemetryManager.trackEventWithName("Hello World event!",
properties:["Test property 1":"Some value",
"Test property 2":"Some other value"],
measurements:["Test measurement 1":4.8,
"Test measurement 2":15.16,
"Test measurement 3":23.42])
// Send a message
MSAITelemetryManager.trackTraceWithMessage("Test message")
// Manually send pageviews
MSAITelemetryManager.trackPageView("MyViewController",
duration:300,
properties:["Test measurement 1":4.8])
// Send a message
MSAITelemetryManager.trackMetricWithName("Test metric", value:42.2)
The SDK also allows for some more advanced usages.
It is also possible to set so-called "common properties" that will then be automatically attached to all telemetry data items.
[MSAITelemetryManager setCommonProperties:@{@"custom info":@"some value"}];
MSAITelemetryManager.setCommonProperties(["custom info":"some value"])
Automatic collection of lifecycle events is enabled by default. This means that Application Insights automatically manages sessions for you.
By default, the Application Insights for OS X SDK starts a new session when the containing app is restarted (this means a 'cold start', i.e. when the app has not already been in memory prior to being launched) or when it has been in the background for more then 20 seconds.
You can either change this time frame:
[MSAIApplicationInsights setAppBackgroundTimeBeforeSessionExpires:60];
turn of automatic session completely:
[MSAIApplicationInsights setAutoSessionManagementDisabled:YES];
This then requires you to manage sessions manually:
[MSAIApplicationInsights renewSessionWithId:@"4815162342"];
Normally, a random anonymous ID is automatically generated for every user of your app by the SDK. Alternatively you can set your own user ID or other user attributes, which will then be attached to all telemetry events and crashes:
[[MSAIApplicationInsights sharedInstance] setUserWithConfigurationBlock:^(MSAIUser *user) {
user.userId = @"your_user_id";
user.accountId = @"[email protected]";
}];
The Application Insights SDK enables crash reporting per default. Crashes will be immediately sent to the server the next time the app is launched. To provide you with the best crash reporting, we are using PLCrashReporter in Version 1.2 / Commit 273a7e7cd4b77485a584ac82e77b7c857558e2f9.
This feature can be disabled as follows:
[MSAIApplicationInsights setup]; //setup the SDK
[[MSAIApplicationInsights sharedInstance] setCrashManagerDisabled:YES]; //disable crash reporting
[MSAIApplicationInsights start]; //start using the SDK
-
Custom
NSUncaughtExceptionHandler
don't start working until afterNSApplication
has finished calling all of its delegate methods!Example:
``` objectivec - (void)applicationDidFinishLaunching:(NSNotification *)note { ... [NSException raise:@"ExceptionAtStartup" format:@"This will not be recognized!"]; ... } ```
-
The default
NSUncaughtExceptionHandler
inNSApplication
only logs exceptions to the console and ends their processing. Resulting in exceptions that occur in theNSApplication
"scope" not occurring in a registered customNSUncaughtExceptionHandler
.Example:
``` objectivec - (void)applicationDidFinishLaunching:(NSNotification *)note { ... [self performSelector:@selector(delayedException) withObject:nil afterDelay:5]; ... } - (void)delayedException { NSArray *array = [NSArray array]; [array objectAtIndex:23]; } ```
-
Any exceptions occurring in IBAction or other GUI does not even reach the NSApplication default UncaughtExceptionHandler.
Example:
``` objectivec - (IBAction)doExceptionCrash:(id)sender { NSArray *array = [NSArray array]; [array objectAtIndex:23]; } ```
In general there are two solutions. The first one is to use an NSExceptionHandler
class instead of an NSUncaughtExceptionHandler
. But this has a few drawbacks which are detailed in MSAICrashExceptionApplication.h
.
Instead we provide the optional NSApplication
subclass MSAICrashExceptionApplication
which handles cases 2 and 3.
Installation:
- Open the applications
Info.plist
- Search for the field
Principal class
- Replace
NSApplication
withMSAICrashExceptionApplication
Alternatively, if you have your own NSApplication subclass, change it to be a subclass of MSAICrashExceptionApplication
instead.
You can also configure a different server endpoint for the SDK if needed using a full URL
[MSAIApplicationInsights setup]; //setup the SDK
[[MSAIApplicationInsights sharedInstance] setServerURL:@"https://YOURDOMAIN/path/subpath"];
[MSAIApplicationInsights start]; //start using the SDK
Our documentation can be found on CocoaDocs.
We're looking forward to your contributions via pull requests.
Development environment
- Mac running the latest version of OS X
- Get the latest Xcode from the Mac App Store
- AppleDoc
- Cocoapods
If you have further questions or are running into trouble that cannot be resolved by any of the steps here, feel free to contact us at [email protected]