Dynatrace OpenKit API methods

Dynatrace OpenKit offers a number of API methods that enable you to integrate OpenKit into your application. The sections below describe how to use each of these OpenKit methods.

Obtain an OpenKit instance

To obtain a new OpenKit instance, use DynatraceOpenKitBuilder.

String applicationID = "application-id";
long deviceID = Util.getDeviceID();
String endpointURL = "https://tenantid.beaconurl.com/mbeacon";
OpenKit openKit = new DynatraceOpenKitBuilder(endpointURL, applicationID, deviceID).build();

In addition to the mandatory parameters described above, the builder provides additional methods to further customize OpenKit. These include device-specific information like the operating system, manufacturer, or model ID.

Method name
Description
Default value
Since version
withApplicationVersion
Sets the application version
OpenKit version
1.0.1
withOperatingSystem
Sets the operating system name
OpenKit <OpenKit version>
1.0.1
withManufacturer
Sets the manufacturer
Dynatrace
1.0.1
withModelID
Sets the model ID
OpenKitDevice
1.0.1
withBeaconCacheMaxRecordAge
Sets the maximum age of an entry in the beacon cache in milliseconds
1 h 45 min
1.0.1
withBeaconCacheLowerMemoryBoundary
Sets the lower memory boundary of the beacon cache in bytes
80 MB
1.0.1
withBeaconCacheUpperMemoryBoundary
Sets the upper memory boundary of the beacon cache in bytes
100 MB
1.0.1
withLogger
Sets a custom Logger replacing the currently set one
DefaultLogger
1.0.1
withTrustManager
Sets a custom SSLTrustManager replacing the currently set one
SSLStrictTrustManager
1.0.1
withDataCollectionLevel
Sets the data collection level
DataCollectionLevel.USER_BEHAVIOR
1.1.0
withCrashReportingLevel
Sets the crash reporting level
CrashReportingLevel.OPT_IN_CRASHES
1.1.0
withLogLevel
Sets the default log level when the built-in logger is used
LogLevel.WARN
2.0.0
withHttpRequestInterceptor
Sets the Interceptor for requests to Dynatrace backends
NullHttpRequestInterceptor
2.2.0
withHttpResponseInterceptor
Sets the Interceptor for responses received from Dynatrace backends
NullHttpResponseInterceptor
2.2.0

SSL/TLS security

All OpenKit communication to the backend happens via HTTPS. By default, OpenKit expects valid server certificates. However, it is possible, if needed, to bypass certificate validation. You can configure a custom trust manager using the builder.

We do not recommend bypassing TLS/SSL server certificate validation, since this allows man-in-the-middle attacks.

class MyCustomTrustManager implements SSLTrustManager {
// implement interface methods
}
SSLTrustManager trustManager = new MyCustomTrustManager()
OpenKit openKit = new DynatraceOpenKitBuilder(endpointURL, applicationID, deviceID)
.withTrustManager(trustManager)
.build();

Enable verbose logging

By default, OpenKit uses a logger implementation that logs to stdout. If the default logger is used, you can enable verbose logging via DynatraceOpenKitBuilder. When the verbose mode is enabled, info and debug messages are logged.

You can also configure a custom logger. For details, see Dynatrace OpenKit logging.

Initialize OpenKit

When obtaining an OpenKit instance from the builder, the instance starts an automatic initialization phase. By default, initialization is performed asynchronously.

There might be situations when you need to ensure that initialization is completed before proceeding with the program logic, for example, in case of short-lived applications where a valid init and shutdown cannot be guaranteed. For such applications, OpenKit allows to wait for the initialization in two ways:

  • With timeout: The calling threads waits a given amount of time for OpenKit to initialize. The method returns false in case the timeout expired or a shutdown was performed in the meantime and true to indicate successful initialization.
  • Without timeout: The calling thread blocks until OpenKit is initialized. In case of misconfiguration this might block the calling thread indefinitely. The return value indicates whether the OpenKit instance has been initialized or a shutdown was performed meanwhile.
// wait until the OpenKit instance is fully initialized
boolean success = openKit.waitForInitCompletion();
// wait up to 10 seconds for OpenKit to complete initialization
long timeoutInMilliseconds = 10 * 1000;
boolean success = openKit.waitForInitCompletion(timeoutInMilliseconds);

In addition, OpenKit enables you to verify whether or not it's been initialized.

boolean isInitialized = openKit.isInitialized();
if (isInitialized) {
System.out.println("OpenKit is initialized");
} else {
System.out.println("OpenKit is not yet initialized");
}

Create a session

You can create a new session using the OpenKit instance obtained from the builder. When creating a new session, you can also provide an IP address.

  • If a valid IPv4 or IPv6 address is provided, it is assigned to the session.
  • If no IP address or an invalid IP address is provided, the IP address of the session is auto-detected and assigned on the server side.
// create a session and pass an IP address
String clientIPAddress = "12.34.56.78";
Session sessionWithArgument = openKit.createSession(clientIPAddress);
// create a session and let the IP be assigned on the server side
// this overloaded method is available since OpenKit Java 1.4.0
Session sessionWithoutArgument = openKit.createSession();

Tag specific users

You can tag the user assigned to a session. This enables you to search and filter specific user sessions and analyze individual user behavior over time in the backend. See User tagging for more details.

session.identifyUser("jane.doe@example.com");

When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.

Finish a session

When a session is no longer needed, you should end it explicitly. Although all open sessions are automatically ended when OpenKit is shut down, it's highly recommended to manually end sessions that are no longer in use.

session.end();
session = null; // not needed, just used to indicate that the session is no longer valid.

Report a crash

You can report unexpected application crashes on a session. The crash details are sent immediately after you've reported a crash.

private static int div(int numerator, int denominator) {
return numerator / denominator;
}
public static void divWithCrash() {
int numerator = 5;
int denominator = 0;
try {
System.out.println("Got: " + div(numerator, denominator));
} catch (Exception e) {
String errorName = e.getClass().getName();
String reason = e.getMessage();
String stackTrace = getStackTraceAsString(e); // get the stacktrace as string, similar as e.printStackTrace()
// and now report the application crash via the session
session.reportCrash(errorName, reason, stackTrace);
}
}

Create custom and child actions

You can define and report custom actions. After you create a custom action, you can add a child action to it or enhance an action with additional information before finally closing it. You should create custom actions from a session and child actions from a custom action.

String rootActionName = "rootActionName";
String childActionName = "childActionName";
// create a custom action for a session
RootAction rootAction = session.enterAction(rootActionName);
// create a child action for the custom action
Action childAction = rootAction.enterAction(childActionName);

The maximum duration of a user action in custom apps is 10 minutes. When a user action takes longer than this, such an action is discarded and not reported to Dynatrace.

There's no limit on the number of child actions attached to a custom action. However, note that you can have only one level of child actions—you can't create a child action for another child action (child actions can't have their own child actions). Also, refer to User session structure for individual user.

Child actions are not displayed on the user session details page, but you can view them on the waterfall analysis page for a custom action to which these child actions are attached.

When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.

End an action

To record accurate timing information for actions, you should leave actions once they're finished.

Action parentAction = action.leaveAction(); // returns the appropriate custom action
Action parent = parentAction.leaveAction(); // will always return null

Cancel an action

Canceling an action is similar to leaving an action, except that the action is discarded and is not sent to Dynatrace. Open child objects, like child actions and web request tracers, are discarded as well. Child objects that have been closed previously are sent to the backend and might be processed, depending on the event type.

Action parentAction = action.cancelAction(); // returns the appropriate custom action
Action parent = parentAction.cancelAction(); // will always return null

Report an event

You can report named events on actions.

String eventName = "eventName";
action.reportEvent(eventName);
// also report on the RootAction
rootAction.reportEvent(eventName);

When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.

Report a value

The reportValue method allows you to report key-value pairs of metadata that you can later view in the Dynatrace web UI and convert into user action and user session properties. The reported values must be part of a user action.

You can report values of the following data types:

  • 32-bit integer
  • 64-bit integer
  • Double
  • String
// first report a 32-bit int value
String keyIntType = "intType";
int valueInt = 42;
action.reportValue(keyIntType, valueInt);
// then let's report a 64-bit long value
String keyLongType = "longType";
long valueLong = Long.MIN_VALUE;
action.reportValue(keyLongType, valueLong);
// then let's report a double value
String keyDoubleType = "doubleType";
double valueDouble = 3.141592653589793;
action.reportValue(keyDoubleType, valueDouble);
// and also a string value
String keyStringType = "stringType";
String valueString = "The quick brown fox jumps over the lazy dog";
action.reportValue(keyStringType, valueString);

To view the reported values in Dynatrace, go to the details of the user action that should contain that metadata and scroll down to the Reported values section.

User action details page with SDK-reported values

To add action and session properties based on the reported values and then use these properties to create powerful queries, segmentations, and aggregations, see Define user action and user session properties for custom applications.

When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.

Report an error

You can report an error including its name (errorName) and error code (errorCode).

String errorName = "Unknown Error";
int errorCode = 42;
action.reportError(errorName, errorCode);

You can also report the following additional information on the error:

  • required errorName—The human-readable name of the error.
  • optional causeName—The cause leading to the reported error, for example, the exception's class name.
  • optional causeDescription—The description of the cause leading to the error, for example, the exception's description.
  • optional stackTrace or causeStackTrace—The stack trace of the cause leading to the error.

The code snippet below shows how to report errors with additional information.

public void restrictedMethod() {
if (!isUserAuthorized()) {
// user is not authorized - report this as an error
String errorName = "Authorization error";
String causeName = "User not authorized";
String causeDescription = "The current user is not authorized to call restrictedMethod.";
String stackTrace = null; // no stack trace is reported
action.reportError(errorName, causeName, causeDescription, stackTrace);
return;
}
// ... further processing ...
}

OpenKit Java and OpenKit .NET offer a convenience API to directly report caught exceptions, as demonstrated in the example below.

try {
// call a method that is throwing an exception
callMethodThrowingException();
} catch(Exception caughtException) {
// report the caught exception as error via OpenKit
String errorName = "Unknown Error";
action.reportError(errorName, caughtException);
}

When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.

Trace web requests

One of the most powerful OpenKit features is web request tracing. When the application starts a web request, for example, HTTP GET, a special tag can be attached to the header. This header allows Dynatrace to correlate actions with a server-side distributed trace. An example is shown below.

// create URL and open URLConnection
URL url = new URL("http://www.my-backend.com/api/v3/users");
URLConnection urlConnection = url.openConnection();
// create the WebRequestTracer
WebRequestTracer webRequestTracer = action.traceWebRequest(urlConnection);
webRequestTracer.start();
// consume data
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// TODO - do something useful with response
}
in.close();
// stop web request tracing when done
webRequestTracer.stop(200); // would use the HTTP response code normally.
// --------------------------------------------
// alternative solution not using URLConnection
// --------------------------------------------
String url = "http://www.my-backend.com/api/v3/users";
// create the WebRequestTracer
WebRequestTracer webRequestTracer = action.traceWebRequest(url);
// this is the HTTP header name & value which needs to be added to the HTTP request.
String headerName = OpenKitConstants.WEBREQUEST_TAG_HEADER;
String headerValue = webRequestTracer.getTag();
webRequestTracer.start();
// perform the request here & do not forget to add the HTTP header
webRequestTracer.setBytesSent(12345); // 12345 bytes sent
webRequestTracer.setBytesReceived(67890); // 67890 bytes received
webRequestTracer.stop(200); // 200 was the response code

Configure data privacy

You can dynamically adjust data privacy settings and build your custom applications in compliance with data protection laws and regulations. The privacy API methods allow you to dynamically change the data collection level and activate or deactivate crash reporting.

Data collection levels

The table below describes the available data collection levels and shows whether user tags and custom user actions, events, values, and errors are reported for a particular level.

Level

Description

User tags, custom events, and custom values

Custom user actions and errors

Off

Monitoring data is not sent

No personal data is sent; all identifiers are randomized on every launch.1

Not applicable

Not applicable

Performance

Only performance, automatically captured data is sent

No personal data is sent; all identifiers are randomized on every launch.

Not applicable

Applicable

User behavior

Performance data and user data is sent

Personal data is sent; OneAgent recognizes and reports users who revisit in the future.2

Applicable

Applicable

1

A single Loading <App> event is sent to track the number of users that opted out.

2

If you haven't configured user tagging and custom event or value reporting, the User behavior level works similarly to the Performance level.

Crash reporting levels

The following crash reporting levels are available.

Level name

Crash reporting

Use this level when…

Off

Not applicable Disabled

You don't need to collect crash reports.

Opt out crashes

Not applicable Disabled

The user of your application has disallowed the collection of crash reports.

Opt in crashes

default

Applicable Enabled

The user of your application has allowed the collection of crash reports.

Set data collection and crash reporting levels

The code examples below show you how to work with the API:

import com.dynatrace.openkit.DataCollectionLevel;
import com.dynatrace.openkit.CrashReportingLevel;
OpenKit openKit = new DynatraceOpenKitBuilder(endpointURL, applicationID, deviceID)
// set a data collection level (user allowed you to capture performance and personal data)
.withDataCollectionLevel(DataCollectionLevel.USER_BEHAVIOR)
// allow crash reporting (user allowed you to collect information on crashes)
.withCrashReportingLevel(CrashReportingLevel.OPT_IN_CRASHES)
.build();

Possible values for the data collection level:

  • DataCollectionLevel.OFF
  • DataCollectionLevel.PERFORMANCE
  • DataCollectionLevel.USER_BEHAVIOR

Possible values for the crash reporting level:

  • CrashReportingLevel.OFF
  • CrashReportingLevel.OPT_OUT_CRASHES
  • CrashReportingLevel.OPT_IN_CRASHES

Terminate an OpenKit instance

When an OpenKit instance is no longer needed, for example, when the application using OpenKit is shut down, you can clear the obtained instance by invoking. A call to shutdown blocks the calling thread up to 10 seconds, while the OpenKit flushes data that hasn't been transmitted yet to the backend.

openKit.shutdown();