harmony 鸿蒙@ohos.hiviewdfx.hiAppEvent (Application Event Logging)

2022-12-13 浏览 (711)

@ohos.hiviewdfx.hiAppEvent (Application Event Logging)

The hiAppEvent module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.

NOTE

The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';

hiAppEvent.write

write(info: AppEventInfo, callback: AsyncCallback<void>): void

Writes events to the event file of the current day through AppEventInfo objects. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
infoAppEventInfoYesApplication event object.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11100001Function is disabled.
11101001Invalid event domain.
11101002Invalid event name.
11101003Invalid number of event parameters.
11101004Invalid string length of the event parameter.
11101005Invalid event parameter name.
11101006Invalid array length of the event parameter.

Example

import { BusinessError } from '@ohos.base';

let eventParams: Record<string, number|string> = {
  "int_data": 100,
  "str_data": "strValue",
};
hiAppEvent.write({
  domain: "test_domain",
  name: "test_event",
  eventType: hiAppEvent.EventType.FAULT,
  params: eventParams,
}, (err: BusinessError) => {
  if (err) {
    console.error(`code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.log(`success to write event`);
});

hiAppEvent.write

write(info: AppEventInfo): Promise<void>

Writes events to the event file of the current day through AppEventInfo objects. This API uses a promise to return the result.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
infoAppEventInfoYesApplication event object.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11100001Function is disabled.
11101001Invalid event domain.
11101002Invalid event name.
11101003Invalid number of event parameters.
11101004Invalid string length of the event parameter.
11101005Invalid event parameter name.
11101006Invalid array length of the event parameter.

Example

import { BusinessError } from '@ohos.base';

let eventParams: Record<string, number|string> = {
  "int_data": 100,
  "str_data": "strValue",
};
hiAppEvent.write({
  domain: "test_domain",
  name: "test_event",
  eventType: hiAppEvent.EventType.FAULT,
  params: eventParams,
}).then(() => {
  console.log(`success to write event`);
}).catch((err: BusinessError) => {
  console.error(`code: ${err.code}, message: ${err.message}`);
});

AppEventInfo

Defines parameters for an AppEventInfo object.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
domainstringYesEvent domain. The value is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It must start with a lowercase letter and cannot end with an underscore (_).
namestringYesEvent name. The value is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).
eventTypeEventTypeYesEvent type.
paramsobjectYesEvent parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:
- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).
- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.

hiAppEvent.configure

configure(config: ConfigOption): void

Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
configConfigOptionYesConfiguration items for application event logging.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11103001Invalid max storage quota value.

Example

// Disable the event logging function.
let config1: hiAppEvent.ConfigOption = {
  disable: true,
};
hiAppEvent.configure(config1);

// Set the maximum size of the file storage directory to 100 MB.
let config2: hiAppEvent.ConfigOption = {
  maxStorage: '100M',
};
hiAppEvent.configure(config2);

ConfigOption

Configures options for application event logging.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
disablebooleanNoWhether to enable the event logging function. The default value is false. The value true means to disable the event logging function, and the value false means the opposite.
maxStoragestringNoMaximum size of the directory that stores event logging files. The default value is 10M.
If the directory size exceeds the specified quota when application event logging is performed, event logging files in the directory will be cleared one by one based on the generation time to ensure that directory size does not exceed the quota.

hiAppEvent.addWatcher

addWatcher(watcher: Watcher): AppEventPackageHolder

Adds a watcher to subscribe to application events.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
watcherWatcherYesWatcher for application events.

Return value

TypeDescription
AppEventPackageHolderSubscription data holder. If the subscription fails, null will be returned.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11102001Invalid watcher name.
11102002Invalid filtering event domain.
11102003Invalid row value.
11102004Invalid size value.
11102005Invalid timeout value.

Example

// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
hiAppEvent.addWatcher({
  name: "watcher1",
  appEventFilters: [
    {
      domain: "test_domain",
      eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
    }
  ],
  triggerCondition: {
    row: 10,
    size: 1000,
    timeOut: 1
  },
  onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => {
    if (holder == null) {
      console.error("holder is null");
      return;
    }
    console.info(`curRow=${curRow}, curSize=${curSize}`);
    let eventPkg: hiAppEvent.AppEventPackage|null = null;
    while ((eventPkg = holder.takeNext()) != null) {
      console.info(`eventPkg.packageId=${eventPkg.packageId}`);
      console.info(`eventPkg.row=${eventPkg.row}`);
      console.info(`eventPkg.size=${eventPkg.size}`);
      for (const eventInfo of eventPkg.data) {
        console.info(`eventPkg.data=${eventInfo}`);
      }
    }
  }
});

// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
let holder = hiAppEvent.addWatcher({
  name: "watcher2",
});
if (holder != null) {
  let eventPkg: hiAppEvent.AppEventPackage|null = null;
  while ((eventPkg = holder.takeNext()) != null) {
    console.info(`eventPkg.packageId=${eventPkg.packageId}`);
    console.info(`eventPkg.row=${eventPkg.row}`);
    console.info(`eventPkg.size=${eventPkg.size}`);
    for (const eventInfo of eventPkg.data) {
      console.info(`eventPkg.data=${eventInfo}`);
    }
  }
}

hiAppEvent.removeWatcher

removeWatcher(watcher: Watcher): void

Removes a watcher to unsubscribe from application events.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
watcherWatcherYesWatcher for application events.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11102001Invalid watcher name.

Example

// 1. Define a watcher for application events.
let watcher: hiAppEvent.Watcher = {
  name: "watcher1",
}

// 2. Add the watcher to subscribe to application events.
hiAppEvent.addWatcher(watcher);

// 3. Remove the watcher to unsubscribe from application events.
hiAppEvent.removeWatcher(watcher);

Watcher

Defines parameters for a Watcher object.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
namestringYesUnique name of the watcher.
triggerConditionTriggerConditionNoSubscription callback triggering condition. This parameter takes effect only when it is passed together with the callback.
appEventFiltersAppEventFilter[]NoSubscription filtering condition. This parameter is passed only when subscription events need to be filtered.
onTrigger(curRow: number, curSize: number, holder: AppEventPackageHolder) => voidNoSubscription callback, which takes effect only when it is passed together with the callback triggering condition. The input arguments are described as follows:
curRow: total number of subscription events when the callback is triggered.
curSize: total size of subscribed events when the callback is triggered, in bytes.
holder: subscription data holder, which can be used to process subscribed events.

TriggerCondition

Defines callback triggering conditions. Subscription callback is triggered when any condition is met.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
rownumberNoNumber of events.
sizenumberNoEvent data size, in bytes.
timeOutnumberNoTimeout interval, in unit of 30s.

AppEventFilter

Defines parameters for an AppEventFilter object.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
domainstringYesEvent domain.
eventTypesEventType[]NoEvent types.

AppEventPackageHolder

Defines a subscription data holder for processing subscription events.

System capability: SystemCapability.HiviewDFX.HiAppEvent

constructor

constructor(watcherName: string)

Constructor of the Watcher class. When a watcher is added, the system automatically calls this API to create a subscription data holder object for the watcher and returns the holder object to the application.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
watcherNamestringYesWatcher name.

Example

let holder1 = hiAppEvent.addWatcher({
    name: "watcher1",
});

setSize

setSize(size: number): void

Sets the threshold for the data size of the application event package obtained each time.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Parameters

NameTypeMandatoryDescription
sizenumberYesData size threshold, in bytes. The default value is 512*1024.

Error codes

For details about the error codes, see Application Event Logging Error Codes.

IDError Message
11104001Invalid size value.

Example

let holder2 = hiAppEvent.addWatcher({
    name: "watcher2",
});
holder2.setSize(1000);

takeNext

takeNext(): AppEventPackage

Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, null will be returned.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Example

let holder3 = hiAppEvent.addWatcher({
    name: "watcher3",
});
let eventPkg = holder3.takeNext();

AppEventPackage

Defines parameters for an AppEventPackage object.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeMandatoryDescription
packageIdnumberYesEvent package ID, which is named from 0 in ascending order.
rownumberYesNumber of events in the event package.
sizenumberYesEvent size of the event package, in bytes.
datastring[]YesEvent data in the event package.

hiAppEvent.clearData

clearData(): void

Clears local application event logging data.

System capability: SystemCapability.HiviewDFX.HiAppEvent

Example

hiAppEvent.clearData();

EventType

Enumerates event types.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameValueDescription
FAULT1Fault event.
STATISTIC2Statistical event.
SECURITY3Security event.
BEHAVIOR4Behavior event.

event

Provides constants that define the names of all predefined events.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeDescription
USER_LOGINstringUser login event.
USER_LOGOUTstringUser logout event.
DISTRIBUTED_SERVICE_STARTstringDistributed service startup event.

param

Provides constants that define the names of all predefined event parameters.

System capability: SystemCapability.HiviewDFX.HiAppEvent

NameTypeDescription
USER_IDstringCustom user ID.
DISTRIBUTED_SERVICE_NAMEstringDistributed service name.
DISTRIBUTED_SERVICE_INSTANCE_IDstringDistributed service instance ID.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/0fe1a45b7ea943fa94f2298aa29de124