• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
2
3<!--Kit: Performance Analysis Kit-->
4<!--Subsystem: HiviewDFX-->
5<!--Owner: @liujiaxing2024-->
6<!--Designer: @junjie_shi-->
7<!--Tester: @gcw_KuLfPSbe-->
8<!--Adviser: @foryourself-->
9
10This module provides application logging and event subscription capabilities, including event storage, event subscription, event clearance, and logging configuration. HiAppEvent records the events triggered during application running in [AppEventInfo](#appeventinfo), and classifies the events into system events and application events.
11
12System events are triggered in system services and are predefined in the system. The fields of the event parameter object **params** of such events are defined by each system event. For details, see overviews of user guides. For example, [Crash Event Overview](../../dfx/hiappevent-watcher-crash-events.md).
13
14Application events are defined by application developers and can be customized using the [Write](#hiappeventwrite-1) API as required.
15
16> **NOTE**
17>
18> 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.
19
20
21## Modules to Import
22
23```ts
24import { hiAppEvent } from '@kit.PerformanceAnalysisKit';
25```
26
27
28## hiAppEvent.addWatcher
29
30addWatcher(watcher: Watcher): AppEventPackageHolder
31
32Adds an event watcher. You can use the callback of the event watcher to subscribe to events.
33
34**Atomic service API**: This API can be used in atomic services since API version 11.
35
36**System capability**: SystemCapability.HiviewDFX.HiAppEvent
37
38**Parameters**
39
40| Name | Type                | Mandatory| Description            |
41| ------- | -------------------- | ---- | ---------------- |
42| watcher | [Watcher](#watcher) | Yes  | Event watcher.|
43
44**Return value**
45
46| Type                                            | Description                                |
47| ------------------------------------------------ | ------------------------------------ |
48| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** is returned.|
49
50**Error codes**
51
52For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
53
54| ID| Error Message                       |
55| -------- | ------------------------------- |
56| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
57| 11102001 | Invalid watcher name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
58| 11102002 | Invalid filtering event domain. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
59| 11102003 | Invalid row value. Possible caused by the row value is less than zero. |
60| 11102004 | Invalid size value. Possible caused by the size value is less than zero. |
61| 11102005 | Invalid timeout value. Possible caused by the timeout value is less than zero. |
62
63**Example**
64
65Based on the type of the event watcher, the following methods are available:
66
67Method 1: Set **triggerCondition** to implement the **onTrigger()** callback. When the callback conditions are met, the system automatically triggers the callback.
68```ts
69import { hilog } from '@kit.PerformanceAnalysisKit';
70
71hiAppEvent.addWatcher({
72  name: "watcher1",
73  // Subscription filters. The application crash event in the system event domain is subscribed.
74  appEventFilters: [
75    {
76      domain: hiAppEvent.domain.OS,
77      names: [hiAppEvent.event.APP_CRASH]
78    }
79  ],
80  // Set the condition for triggering the onTrigger callback. The callback is triggered when the total number of events reaches 10, the total event size reaches 1000 bytes, or the event lasts for more than 30s.
81  triggerCondition: {
82    row: 10,
83    size: 1000,
84    timeOut: 1
85  },
86  // Implement the onTrigger callback with triggerCondition. When the callback condition is met, the callback is triggered. After the callback notification is received, use takeNext() to query the subscribed event.
87  onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => {
88    if (holder == null) {
89      hilog.error(0x0000, 'hiAppEvent', "holder is null");
90      return;
91    }
92    hilog.info(0x0000, 'hiAppEvent', `curRow=${curRow}, curSize=${curSize}`);
93    let eventPkg: hiAppEvent.AppEventPackage | null = null;
94    while ((eventPkg = holder.takeNext()) != null) {
95      hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`);
96      hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`);
97      hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`);
98      for (const eventInfo of eventPkg.data) {
99        hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`);
100      }
101    }
102  }
103});
104```
105
106Method 2: If the **triggerCondition** parameter is not set, use the **holder** object returned by the event subscription to obtain the subscribed event.
107<br>For crash events (**hiAppEvent.event.APP_CRASH**) and freeze events (**hiAppEvent.event.APP_FREEZE**) generated during abnormal exits, the system needs time to capture debug logs. Typically, capture completes within 30 seconds; in extreme cases, it may take up to about 2 minutes.
108<br>When the subscription data holder is used to manually process subscription events, the events may not be generated or the log capture is not complete. Therefore, you are advised to call **takeNext()** to obtain such events again after the process is started.
109
110```ts
111import { hilog } from '@kit.PerformanceAnalysisKit';
112
113let holder: hiAppEvent.AppEventPackageHolder = hiAppEvent.addWatcher({
114  name: "watcher2",
115  // Subscription filters. The application crash event in the system event domain is subscribed.
116  appEventFilters: [
117    {
118      domain: hiAppEvent.domain.OS,
119      names: [hiAppEvent.event.APP_CRASH]
120    }
121  ],
122});
123// Obtain crash events through the subscription data holder.
124if (holder != null) {
125  let eventPkg: hiAppEvent.AppEventPackage | null = null;
126  while ((eventPkg = holder.takeNext()) != null) {
127    hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`);
128    hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`);
129    hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`);
130    for (const eventInfo of eventPkg.data) {
131      hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`);
132    }
133  }
134}
135```
136
137Method 3: Implement the **onReceive()** callback, which is triggered in real time when the subscribed event occurs.
138
139```ts
140import { hilog } from '@kit.PerformanceAnalysisKit';
141
142hiAppEvent.addWatcher({
143  name: "watcher3",
144  // Subscription filters. The application crash event in the system event domain is subscribed.
145  appEventFilters: [
146    {
147      domain: hiAppEvent.domain.OS,
148      names: [hiAppEvent.event.APP_CRASH]
149    }
150  ],
151  // Implement the onReceive callback, which is called in real time after an event is detected.
152  onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => {
153    hilog.info(0x0000, 'hiAppEvent', `domain=${domain}`);
154    for (const eventGroup of appEventGroups) {
155      hilog.info(0x0000, 'hiAppEvent', `eventName=${eventGroup.name}`);
156      for (const eventInfo of eventGroup.appEventInfos) {
157        hilog.info(0x0000, 'hiAppEvent', `event=${JSON.stringify(eventInfo)}`, );
158      }
159    }
160  }
161});
162```
163
164
165## hiAppEvent.removeWatcher
166
167removeWatcher(watcher: Watcher): void
168
169Removes an event watcher.
170
171**Atomic service API**: This API can be used in atomic services since API version 11.
172
173**System capability**: SystemCapability.HiviewDFX.HiAppEvent
174
175**Parameters**
176
177| Name | Type                | Mandatory| Description            |
178| ------- | -------------------- | ---- | ---------------- |
179| watcher | [Watcher](#watcher) | Yes  | Event watcher.|
180
181**Error codes**
182
183For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
184
185| ID| Error Message             |
186| -------- | --------------------- |
187| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
188| 11102001 | Invalid watcher name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
189
190**Example**
191
192```ts
193// 1. Define an event watcher.
194let watcher: hiAppEvent.Watcher = {
195  name: "watcher1",
196}
197
198// 2. Add an event watcher to subscribe to events.
199hiAppEvent.addWatcher(watcher);
200
201// 3. Remove the event watcher to unsubscribe from events.
202hiAppEvent.removeWatcher(watcher);
203```
204
205
206## hiAppEvent.setEventParam<sup>12+</sup>
207
208setEventParam(params: Record&lt;string, ParamType&gt;, domain: string, name?: string): Promise&lt;void&gt;
209
210Sets custom event parameters. This API uses a promise to return the result. In the same lifecycle, system events and application events can be associated by event domain and event name. System events support only JS memory leaks in [crash events](../../dfx/hiappevent-watcher-crash-events.md), [freeze events](../../dfx/hiappevent-watcher-freeze-events.md), and [resource leak events](../../dfx/hiappevent-watcher-resourceleak-events.md).
211
212**Atomic service API**: This API can be used in atomic services since API version 12.
213
214**System capability**: SystemCapability.HiviewDFX.HiAppEvent
215
216**Parameters**
217
218| Name| Type                          | Mandatory| Description          |
219| ------ | ------------------------------ | ---- | -------------- |
220| params | Record&lt;string, [ParamType](#paramtype12)&gt; | Yes| Custom parameter object. The parameter name and value are defined as follows:<br>- A parameter name is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign (`$`). It must start with a letter or dollar sign (`$`) and end with a digit or letter.  <br>- The parameter value is of the [ParamType](#paramtype12) and contains a maximum of 1024 characters.<br>- The number of parameters must be less than 64.|
221| domain | string                        | Yes| Event domain. The event domain can be associated with application events and system events (hiAppEvent.domain.OS).|
222| name   | string                        | No| Event name. The default value is an empty string, which indicates all event names in the associated event domain. You can use event names to associate application events with system events. System events can be associated only with crash events (**hiAppEvent.event.APP_CRASH**) and freeze events (**hiAppEvent.event.APP_FREEZE**).|
223
224**Return value**
225
226| Type               | Description         |
227| ------------------- | ------------- |
228| Promise&lt;void&gt; | Promise that returns no value.  |
229
230**Error codes**
231
232For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
233
234| ID| Error Message                                     |
235| -------- | --------------------------------------------- |
236| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
237| 11100001 | Function disabled. Possible caused by the param disable in ConfigOption is true. |
238| 11101001 | Invalid event domain. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
239| 11101002 | Invalid event name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
240| 11101004 | Invalid string length of the event parameter. |
241| 11101005 | Invalid event parameter name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
242| 11101007 | The number of parameter keys exceeds the limit. |
243
244**Example**
245
246```ts
247import { BusinessError } from '@kit.BasicServicesKit';
248import { hilog } from '@kit.PerformanceAnalysisKit';
249
250let params: Record<string, hiAppEvent.ParamType> = {
251  "int_data": 100,
252  "str_data": "strValue",
253};
254
255// Add custom parameters to the application event.
256hiAppEvent.setEventParam(params, "test_domain", "test_event").then(() => {
257  hilog.info(0x0000, 'hiAppEvent', `success to set event param`);
258}).catch((err: BusinessError) => {
259  hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
260});
261```
262
263
264## hiAppEvent.setEventConfig<sup>15+</sup>
265
266setEventConfig(name: string, config: Record&lt;string, ParamType&gt;): Promise&lt;void&gt;
267
268Sets event configuration. This method uses a promise to return the result. In the same lifecycle, you can set event configuration by event name.<br>Different events have different configuration items. Currently, only the **MAIN_THREAD_JANK** (For details about the parameter configuration, see [Main Thread Jank Event Overview](../../dfx/hiappevent-watcher-mainthreadjank-events.md#custom-parameters).) and **APP_CRASH** (For details about the parameter configuration, see [Customizing Crash Log Specifications](../../dfx/hiappevent-watcher-crash-events.md#customizing-crash-log-specifications).) events are supported.
269
270**Atomic service API**: This API can be used in atomic services since API version 15.
271
272**System capability**: SystemCapability.HiviewDFX.HiAppEvent
273
274**Parameters**
275
276| Name| Type                          | Mandatory| Description          |
277| ------ | ------------------------------ | ---- | -------------- |
278| name   | string                        | Yes| Event name.|
279| config | Record<string, ParamType> | Yes| Custom parameter object. The parameter name and value are defined as follows:<br>- The parameter name contains a maximum of 1024 characters, which is of the string type and cannot be empty.<br>- The parameter value is of the ParamType and contains a maximum of 1024 characters.|
280
281**Return value**
282
283| Type               | Description         |
284| ------------------- | ------------- |
285| Promise&lt;void&gt; | Promise used to return the result.|
286
287**Error codes**
288
289For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
290
291| ID| Error Message                                     |
292| -------- | --------------------------------------------- |
293| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed. |
294
295**Example**
296
297The following example sets the collection stack parameters of the **MAIN_THREAD_JANK** event:
298
299```ts
300import { BusinessError } from '@kit.BasicServicesKit';
301import { hilog } from '@kit.PerformanceAnalysisKit';
302
303let params: Record<string, hiAppEvent.ParamType> = {
304  "log_type": "1",
305  "sample_interval": "100",
306  "ignore_startup_time": "11",
307  "sample_count": "21",
308  "report_times_per_app": "3"
309};
310hiAppEvent.setEventConfig(hiAppEvent.event.MAIN_THREAD_JANK, params).then(() => {
311  hilog.info(0x0000, 'hiAppEvent', `Successfully set sampling stack parameters.`);
312}).catch((err: BusinessError) => {
313hilog.error(0x0000, 'hiAppEvent', `Failed to set sample stack value. Code: ${err.code}, message: ${err.message}`);
314});
315```
316
317## Watcher
318
319Defines parameters for a **Watcher** object. This API is used to configure and manage event watchers to subscribe to and process specified events.
320
321**Atomic service API**: This API can be used in atomic services since API version 11.
322
323**System capability**: SystemCapability.HiviewDFX.HiAppEvent
324
325| Name            | Type                                               |  Read Only | Optional| Description                                                        |
326| ---------------- | ----------------------------------------------------|------ | ---- | ------------------------------------------------------------ |
327| name             | string                                              |  No  | No  | Unique name of a watcher. The value contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscore (_). It must start with a letter and end with a digit or letter. For example, **testName1** and **crash_Watcher**.                            |
328| triggerCondition | [TriggerCondition](#triggercondition)               |  No  | Yes  | Subscription callback triggering condition. This parameter takes effect only when it is passed together with **onTrigger**. If this parameter is not set, the **onTrigger** callback is not triggered by default.          |
329| appEventFilters  | [AppEventFilter](#appeventfilter)[]                 |  No  | Yes  | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered. If this parameter is not set, events are not filtered by default.              |
330| onTrigger        | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void |  No  | Yes  | Subscription callback. This parameter takes effect only when it is passed together with **triggerCondition**. The input arguments are described as follows:<br>**curRow**: total number of subscription events when the callback is triggered.<br>**curSize**: total size of subscribed events when the callback is triggered, in bytes.<br>**holder**: subscription data holder, which can be used to process subscribed events.|
331| onReceive<sup>11+</sup>        | (domain: string, appEventGroups: Array<[AppEventGroup](#appeventgroup11)>) => void |  No  | Yes| Real-time subscription callback. Only this callback function is triggered if it is passed together with **onTrigger**. The input arguments are described as follows:<br>domain: domain name.<br>appEventGroups: event group.|
332
333
334## TriggerCondition
335
336Defines the triggering condition parameters of the **onTrigger** callback of a [Watcher](#watcher).
337
338**Atomic service API**: This API can be used in atomic services since API version 11.
339
340**System capability**: SystemCapability.HiviewDFX.HiAppEvent
341
342| Name   | Type  | Read Only| Optional| Description                                  |
343| ------- | ------ | ---- | ---- | -------------------------------------- |
344| row     | number | No| Yes  | Total number of events that trigger callback. The value is a positive integer. The default value is 0, indicating that no callback is triggered. If this parameter is set to a negative value, the default value is used.            |
345| size    | number | No| Yes  | Total size of events that trigger callback. The value is a positive integer, in bytes. The default value is 0, indicating that no callback is triggered. If this parameter is set to a negative value, the default value is used.|
346| timeOut | number | No| Yes  | Timeout interval for triggering callback. The value is a positive integer, in unit of 30s. The default value is 0, indicating that no callback is triggered. If this parameter is set to a negative value, the default value is used.   |
347
348
349## AppEventFilter
350
351Defines parameters of subscription filtering conditions of a [Watcher](#watcher). This API is used to set event filtering conditions in the event watcher to ensure that only the events that meet the filtering conditions are subscribed to.
352
353**Atomic service API**: This API can be used in atomic services since API version 11.
354
355**System capability**: SystemCapability.HiviewDFX.HiAppEvent
356
357| Name      | Type                     | Read Only| Optional| Description                    |
358| ---------- | ------------------------- | ---- | ---- | ------------------------ |
359| domain     | string                    | No| No  | Event domain, which can be the system event domain (**hiAppEvent.domain.OS**) or the event domain of the custom event information ([AppEventInfo](#appeventinfo)) passed through the [Write](#hiappeventwrite-1) API.    |
360| eventTypes | [EventType](#eventtype)[] | No| Yes  | Event types. If this parameter is not set, events are not filtered by default.|
361| names<sup>11+</sup>      | string[]                  | No| Yes  | Names of the events to be subscribed. If this parameter is not set, events are not filtered by default.|
362
363> **NOTE**
364>
365> In system events, address sanitizer events and task execution timeout events cannot be subscribed to in atomic services. Time-consuming launch events, frame loss events, high CPU load events, and battery usage statistics events cannot be subscribed to in atomic services and application clones.
366
367## AppEventPackageHolder
368
369Defines a subscription data holder for processing event information.
370
371### constructor
372
373constructor(watcherName: string)
374
375Constructs an **AppEventPackageHolder** instance. You can call [addWatcher](#hiappeventaddwatcher) to add an event watcher, and then associate the **AppEventPackageHolder** instance with the watcher added in the application based on the watcher name.
376
377**Atomic service API**: This API can be used in atomic services since API version 11.
378
379**System capability**: SystemCapability.HiviewDFX.HiAppEvent
380
381**Parameters**
382
383| Name| Type             | Mandatory| Description                    |
384| ------ | ----------------- | ---- | ------------------------ |
385| watcherName | string | Yes  | Name of the event watcher added through [addWatcher](#hiappeventaddwatcher). If no watcher is added, no data is displayed by default.|
386
387**Example**
388
389```ts
390// Add the Watcher1 to subscribe to system events.
391hiAppEvent.addWatcher({
392  name: "Watcher1",
393  appEventFilters: [
394    {
395      domain: hiAppEvent.domain.OS,
396    }
397  ],
398  });
399
400// Create an AppEventPackageHolder instance. holder1 holds the event data subscribed by Watcher1 added through addWatcher.
401let holder1: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("Watcher1");
402```
403
404### setSize
405
406setSize(size: number): void
407
408Sets the threshold for the data size of the event package obtained each time.
409
410**Atomic service API**: This API can be used in atomic services since API version 11.
411
412**System capability**: SystemCapability.HiviewDFX.HiAppEvent
413
414**Parameters**
415
416| Name| Type  | Mandatory| Description                                        |
417| ------ | ------ | ---- | -------------------------------------------- |
418| size   | number | Yes  | Data size threshold, in bytes. The value range is [0, 2^31-1]. If the value is out of the range, an exception is thrown.|
419
420**Error codes**
421
422For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
423
424| ID| Error Message           |
425| -------- | ------------------- |
426| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
427| 11104001 | Invalid size value. Possible caused by the size value is less than or equal to zero. |
428
429**Example**
430
431```ts
432// Create an AppEventPackageHolder instance. holder2 holds the event data subscribed by Watcher1 added through addWatcher.
433let holder2: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("Watcher1");
434// Set the data size threshold for obtaining the event package each time to 1000 bytes.
435holder2.setSize(1000);
436```
437
438### setRow<sup>12+</sup>
439
440setRow(size: number): void
441
442Sets the number of data records of the event package obtained each time. When **setRow()** and **setSize()** are called at the same time, only **setRow()** takes effect.
443
444**Atomic service API**: This API can be used in atomic services since API version 12.
445
446**System capability**: SystemCapability.HiviewDFX.HiAppEvent
447
448**Parameters**
449
450| Name| Type  | Mandatory| Description                                        |
451| ------ | ------ | ---- | -------------------------------------------- |
452| size   | number | Yes  | Number of events. The value range is (0, 2^31-1]. If the value is out of the range, an exception is thrown.|
453
454**Error codes**
455
456For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
457
458| ID| Error Message           |
459| -------- | ------------------- |
460| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
461| 11104001 | Invalid size value. Possible caused by the size value is less than or equal to zero. |
462
463**Example**
464
465```ts
466// Create an AppEventPackageHolder instance. holder3 holds the event data subscribed by Watcher1 added through addWatcher.
467let holder3: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("Watcher1");
468// Set the number of data records for obtaining the event package each time to 1000.
469holder3.setRow(1000);
470```
471
472### takeNext
473
474takeNext(): AppEventPackage
475
476Obtains the subscription event.
477
478The system obtains the subscription event data based on the data size threshold specified by **setSize** or the number of data records specified by **setRow**. By default, one subscription event data record is obtained. When all subscription event data is obtained, **null** is returned.
479
480When **setRow** and **setSize** are called at the same time, only **setRow** takes effect.
481
482**Atomic service API**: This API can be used in atomic services since API version 11.
483
484**System capability**: SystemCapability.HiviewDFX.HiAppEvent
485
486**Return value**
487
488| Type                               | Description                                                  |
489| ----------------------------------- | ------------------------------------------------------ |
490| [AppEventPackage](#appeventpackage) | Event package object. If all subscription event data has been retrieved, **null** is returned.|
491
492**Example**
493
494```ts
495// Create an AppEventPackageHolder instance. holder4 holds the event data subscribed by Watcher1 added through addWatcher.
496let holder4: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("Watcher1");
497// Obtain the subscribed event.
498let eventPkg: hiAppEvent.AppEventPackage | null = holder4.takeNext();
499```
500
501
502## AppEventInfo
503
504Defines parameters of the event information.
505
506**Atomic service API**: This API can be used in atomic services since API version 11.
507
508**System capability**: SystemCapability.HiviewDFX.HiAppEvent
509
510| Name     | Type                   | Read Only| Optional| Description                                                        |
511| --------- | ----------------------- | ---- | ---- | ------------------------------------------------------------ |
512| domain    | string                  | No| No  | Event domain. The value is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).|
513| name      | string                  | No| No  | Event name. The value is string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign (`$`). It must start with a letter or dollar sign (`$`) and end with a digit or letter.|
514| eventType | [EventType](#eventtype) | No| No  | Event type.                                                  |
515| params    | object                  | No| No  | Event parameter object, which consists of a parameter name and a parameter value. In system events, the fields contained in **params** are defined by system. For details about the fields, you can see the overviews of system events, for example, [Crash Event Overview](../../dfx/hiappevent-watcher-crash-events.md). For application events, you need to define the parameters of the [Write](#hiappeventwrite-1) API. The specifications are as follows:<br>- A parameter name is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign (`$`). It must start with a letter or dollar sign (`$`) and end with a digit or letter. For example, **testName** and **\$123_name**.<br>- The parameter value can be a string, number, boolean, or array. The string type parameter can contain a maximum of 8 x 1024 characters. If the length exceeds the limit, the parameter and its name will be discarded. The value of the number type parameter must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value exceeds the range, an uncertain value may be generated. The element type in the array type parameter can only be string, number, or boolean. The number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
516
517
518## AppEventPackage
519
520Defines parameters of an **AppEventPackage** object. This API is used to obtain detail information about an event package, which is obtained using the [takeNext](#takenext) API.
521
522**System capability**: SystemCapability.HiviewDFX.HiAppEvent
523
524| Name     | Type    | Read Only| Optional| Description                          |
525| --------- | -------- | ---- | ---- | ------------------------------ |
526| packageId | number   | No| No  | Event package ID, which is named from **0** in ascending order.<br>**Atomic service API**: This API can be used in atomic services since API version 11.   |
527| row       | number   | No| No  | Number of events in the event package.<br>**Atomic service API**: This API can be used in atomic services since API version 11.            |
528| size      | number   | No| No  | Event size of the event package, in bytes.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
529| data      | string[] | No| No  | Event data in the event package.<br>**Atomic service API**: This API can be used in atomic services since API version 11.            |
530| appEventInfos<sup>12+</sup> | Array<[AppEventInfo](#appeventinfo)> | No| No  | Event object group.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
531
532
533## AppEventGroup<sup>11+</sup>
534
535Defines parameters of the event group returned by the subscription. This API can be used to obtain detail information about an event group, which is often used in the **onReceive** callback of [Watcher](#watcher).
536
537**Atomic service API**: This API can be used in atomic services since API version 11.
538
539**System capability**: SystemCapability.HiviewDFX.HiAppEvent
540
541| Name         | Type                           | Read Only| Optional | Description         |
542| ------------- | ------------------------------- | ---- | ---- | ------------- |
543| name          | string                          | No| No  | Event name.    |
544| appEventInfos | Array<[AppEventInfo](#appeventinfo)> | No| No  | Event object group.|
545
546
547## hiAppEvent.write
548
549write(info: AppEventInfo, callback: AsyncCallback&lt;void&gt;): void
550
551Writes events of the **AppEventInfo** type. This API uses an asynchronous callback to return the result. The event object written by calling this API is a custom object. To avoid conflicts with system events, you are not advised to write it to system events (system event name constants defined in [Event](#hiappeventevent)). The events written by this API can be subscribed to through ([addWatcher](#hiappeventaddwatcher)).
552
553**Atomic service API**: This API can be used in atomic services since API version 11.
554
555**System capability**: SystemCapability.HiviewDFX.HiAppEvent
556
557**Parameters**
558
559| Name  | Type                          | Mandatory| Description          |
560| -------- | ------------------------------ | ---- | -------------- |
561| info     | [AppEventInfo](#appeventinfo) | Yes  | Application event object. You are advised to avoid the conflict between the custom event name and the system event name constant defined in [Event](#hiappeventevent).|
562| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result.|
563
564**Error codes**
565
566For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
567
568| ID| Error Message                                     |
569| -------- | --------------------------------------------- |
570| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
571| 11100001 | Function disabled. Possible caused by the param disable in ConfigOption is true. |
572| 11101001 | Invalid event domain. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
573| 11101002 | Invalid event name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
574| 11101003 | Invalid number of event parameters. Possible caused by the number of parameters is over 32. |
575| 11101004 | Invalid string length of the event parameter. |
576| 11101005 | Invalid event parameter name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
577| 11101006 | Invalid array length of the event parameter. |
578
579**Example**
580
581```ts
582import { BusinessError } from '@kit.BasicServicesKit';
583import { hilog } from '@kit.PerformanceAnalysisKit';
584
585let eventParams: Record<string, number | string> = {
586  "int_data": 100,
587  "str_data": "strValue",
588};
589
590// Application event logging. This API uses an asynchronous callback to return the result.
591hiAppEvent.write({
592  domain: "test_domain",
593  name: "test_event",
594  eventType: hiAppEvent.EventType.FAULT,
595  params: eventParams,
596}, (err: BusinessError) => {
597  if (err) {
598    hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
599    return;
600  }
601  hilog.info(0x0000, 'hiAppEvent', `success to write event`);
602});
603```
604
605
606## hiAppEvent.write
607
608write(info: AppEventInfo): Promise&lt;void&gt;
609
610Writes events of the **AppEventInfo** type. This API uses a promise to return the result. The event object written by calling this API is a custom object. To avoid conflicts with system events, you are not advised to write it to system events (system event name constants defined in [Event](#hiappeventevent)). The events written by this API can be subscribed to through ([addWatcher](#hiappeventaddwatcher)).
611
612**Atomic service API**: This API can be used in atomic services since API version 11.
613
614**System capability**: SystemCapability.HiviewDFX.HiAppEvent
615
616**Parameters**
617
618| Name| Type                          | Mandatory| Description          |
619| ------ | ------------------------------ | ---- | -------------- |
620| info   | [AppEventInfo](#appeventinfo) | Yes  | Application event object. You are advised to avoid the conflict between the custom event name and the system event name constant defined in [Event](#hiappeventevent).|
621
622**Return value**
623
624| Type               | Description         |
625| ------------------- | ------------- |
626| Promise&lt;void&gt; | Promise that returns no value.  |
627
628**Error codes**
629
630For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
631
632| ID| Error Message                                     |
633| -------- | --------------------------------------------- |
634| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
635| 11100001 | Function disabled. Possible caused by the param disable in ConfigOption is true. |
636| 11101001 | Invalid event domain. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
637| 11101002 | Invalid event name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
638| 11101003 | Invalid number of event parameters. Possible caused by the number of parameters is over 32. |
639| 11101004 | Invalid string length of the event parameter. |
640| 11101005 | Invalid event parameter name. Possible causes: 1. Contain invalid characters; 2. Length is invalid. |
641| 11101006 | Invalid array length of the event parameter. |
642
643**Example**
644
645```ts
646import { BusinessError } from '@kit.BasicServicesKit';
647import { hilog } from '@kit.PerformanceAnalysisKit';
648
649let eventParams: Record<string, number | string> = {
650  "int_data": 100,
651  "str_data": "strValue",
652};
653
654// Application event logging. This API uses a promise to return the result.
655hiAppEvent.write({
656  domain: "test_domain",
657  name: "test_event",
658  eventType: hiAppEvent.EventType.FAULT,
659  params: eventParams,
660}).then(() => {
661  hilog.info(0x0000, 'hiAppEvent', `success to write event`);
662}).catch((err: BusinessError) => {
663  hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
664});
665```
666
667
668## hiAppEvent.addProcessor<sup>11+</sup>
669
670addProcessor(processor: Processor): number
671
672Adds the configuration information of the data processor, such as the event name received by it.
673
674This is a synchronous API and involves time-consuming operations. To ensure performance, you are advised to use the asynchronous API [addProcessorFromConfig](#hiappeventaddprocessorfromconfig20) or use a child thread.
675
676**Atomic service API**: This API can be used in atomic services since API version 11.
677
678**System capability**: SystemCapability.HiviewDFX.HiAppEvent
679
680**Parameters**
681
682| Name    | Type       | Mandatory| Description             |
683| ---------  | ---------- | ---- | -------------    |
684| processor  | [Processor](#processor11)  | Yes  | Data processor.|
685
686**Return value**
687
688| Type   | Description                  |
689| ------ | ---------------------- |
690| number | ID of the data processor of the reported event, which uniquely identifies the data processor and can be used to remove the data processor. If the operation fails, **-1** is returned. If the operation is successful, a value greater than **0** is returned.|
691
692**Error codes**
693
694| ID| Error Message         |
695| ------- | ----------------- |
696| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
697
698**Example**
699
700```ts
701import { hilog } from '@kit.PerformanceAnalysisKit';
702
703try {
704    let processor: hiAppEvent.Processor = {
705      name: 'analytics_demo'
706    };
707    let id: number = hiAppEvent.addProcessor(processor);
708    hilog.info(0x0000, 'hiAppEvent', `addProcessor event was successful, id=${id}`);
709} catch (error) {
710    hilog.error(0x0000, 'hiAppEvent', `failed to addProcessor event, code=${error.code}`);
711}
712```
713
714
715## hiAppEvent.addProcessorFromConfig<sup>20+</sup>
716
717addProcessorFromConfig(processorName: string, configName?: string): Promise&lt;number&gt;
718
719<!--RP1-->
720
721Adds the configuration information of the data processor. The configuration file contains information such as the name of the event received by the data processor. This API uses a promise to return the result.
722<!--RP1End-->
723
724**Atomic service API**: This API can be used in atomic services since API version 20.
725
726**System capability**: SystemCapability.HiviewDFX.HiAppEvent
727
728**Parameters**
729
730| Name    | Type       | Mandatory| Description             |
731| ---------  | ---------- | ---- | -------------    |
732| processorName  |  string  | Yes  | <!--RP2-->Name of a data processor, which can contain only letters, digits, underscores (_), and dollar signs ($). It cannot start with a digit and cannot exceed 256 characters.<!--RP2End-->|
733| configName  |  string  | No  | <!--RP3-->Name of the data processor configuration. The corresponding configuration can be loaded from the configuration file. The default value is **SDK_OCG**. It can contain only letters, digits, underscores (_), and dollar signs ($). It cannot start with a digit and cannot exceed 256 characters.<!--RP3End-->|
734
735**Return value**
736
737| Type   | Description                  |
738| ------ | ---------------------- |
739| Promise&lt;number&gt; | Promise that returns the unique ID of the added event data processor, which can be used to remove the data processor. If the adding fails, error code **11105001** is returned.|
740
741**Error codes**
742
743| ID| Error Message         |
744| ------- | ----------------- |
745| 11105001     | Invalid parameter value. Possible causes: 1. Incorrect parameter length; 2. Incorrect parameter format. |
746
747**Example**
748
749```ts
750import { BusinessError } from '@kit.BasicServicesKit';
751import { hilog } from '@kit.PerformanceAnalysisKit';
752
753hiAppEvent.addProcessorFromConfig("test_name").then((processorId) => {
754  hilog.info(0x0000, 'hiAppEvent', `Succeeded in adding processor from config, processorId=${processorId}`);
755}).catch((err: BusinessError) => {
756  hilog.error(0x0000, 'hiAppEvent', `Failed to add processor from config, code: ${err.code}, message: ${err.message}`);
757});
758```
759
760
761## hiAppEvent.removeProcessor<sup>11+</sup>
762
763removeProcessor(id: number): void
764
765Removes the data processor of a reported event.
766
767**Atomic service API**: This API can be used in atomic services since API version 11.
768
769**System capability**: SystemCapability.HiviewDFX.HiAppEvent
770
771**Parameters**
772
773| Name| Type   | Mandatory| Description                        |
774| ------| ------- | ---- | --------------------------- |
775| id    | number  | Yes  | ID of a data processor. The value must be greater than **0**. The value is obtained by calling [addProcessor](#hiappeventaddprocessor11).|
776
777**Error codes**
778
779| ID| Error Message         |
780| ------- | ----------------- |
781| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
782
783**Example**
784
785```ts
786import { hilog } from '@kit.PerformanceAnalysisKit';
787
788try {
789    let processor: hiAppEvent.Processor = {
790      name: 'analytics_demo'
791    };
792    let id: number = hiAppEvent.addProcessor(processor);
793    // Remove a specified data processor based on the ID returned after the data processor is added.
794    hiAppEvent.removeProcessor(id);
795} catch (error) {
796    hilog.error(0x0000, 'hiAppEvent', `failed to removeProcessor event, code=${error.code}`);
797}
798```
799
800
801## hiAppEvent.setUserId<sup>11+</sup>
802
803setUserId(name: string, value: string): void
804
805Sets a user ID, which is used for association when a [Processor](#processor11) is configured.
806
807**Atomic service API**: This API can be used in atomic services since API version 11.
808
809**System capability**: SystemCapability.HiviewDFX.HiAppEvent
810
811**Parameters**
812
813| Name    | Type                     | Mandatory| Description          |
814| --------- | ------------------------- | ---- | -------------  |
815| name      | string                    | Yes  | Key of a user ID. The value is string that contains a maximum of 256 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign ($). It must not start with a digit.  |
816| value     | string                    | Yes  | Value of a user ID. It can contain a maximum of 256 characters. If the value is **null** or left empty, the user ID is cleared.|
817
818**Error codes**
819
820| ID| Error Message         |
821| ------- | ----------------- |
822| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
823
824**Example**
825
826```ts
827import { hilog } from '@kit.PerformanceAnalysisKit';
828
829try {
830  hiAppEvent.setUserId('key', 'value');
831} catch (error) {
832  hilog.error(0x0000, 'hiAppEvent', `failed to setUserId event, code=${error.code}`);
833}
834```
835
836
837## hiAppEvent.getUserId<sup>11+</sup>
838
839getUserId(name: string): string
840
841Obtains the value set through **setUserId**.
842
843**Atomic service API**: This API can be used in atomic services since API version 11.
844
845**System capability**: SystemCapability.HiviewDFX.HiAppEvent
846
847**Parameters**
848
849| Name    | Type                   | Mandatory| Description        |
850| --------- | ----------------------- | ---- | ----------  |
851| name      | string                  | Yes  | Key of a user ID. The value is string that contains a maximum of 256 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign ($). It must not start with a digit.|
852
853**Return value**
854
855| Type   | Description                           |
856| ------ | ------------------------------- |
857| string | Value of a user ID. If no user ID is found, an empty string is returned.|
858
859**Error codes**
860
861| ID| Error Message         |
862| ------- | ----------------- |
863| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
864
865**Example**
866
867```ts
868import { hilog } from '@kit.PerformanceAnalysisKit';
869
870hiAppEvent.setUserId('key', 'value');
871try {
872  let value: string = hiAppEvent.getUserId('key');
873  hilog.info(0x0000, 'hiAppEvent', `getUserId event was successful, userId=${value}`);
874} catch (error) {
875  hilog.error(0x0000, 'hiAppEvent', `failed to getUserId event, code=${error.code}`);
876}
877```
878
879
880## hiAppEvent.setUserProperty<sup>11+</sup>
881
882setUserProperty(name: string, value: string): void
883
884Sets a user property, which is used for association when a [Processor](#processor11) is configured.
885
886**Atomic service API**: This API can be used in atomic services since API version 11.
887
888**System capability**: SystemCapability.HiviewDFX.HiAppEvent
889
890**Parameters**
891
892| Name    | Type                     | Mandatory| Description          |
893| --------- | ------------------------- | ---- | -------------- |
894| name      | string                    | Yes  | Key of a user property. The value is string that contains a maximum of 256 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign ($). It must not start with a digit. |
895| value     | string                    | Yes  | Value of a user property. It can contain a maximum of 1024 characters. If the value is **null** or left empty, the user property is cleared. |
896
897**Error codes**
898
899| ID| Error Message         |
900| ------- | ----------------- |
901| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
902
903**Example**
904
905```ts
906import { hilog } from '@kit.PerformanceAnalysisKit';
907
908try {
909  hiAppEvent.setUserProperty('key', 'value');
910} catch (error) {
911  hilog.error(0x0000, 'hiAppEvent', `failed to setUserProperty event, code=${error.code}`);
912}
913```
914
915
916## hiAppEvent.getUserProperty<sup>11+</sup>
917
918getUserProperty(name: string): string
919
920Obtains the value set through **setUserProperty**.
921
922**Atomic service API**: This API can be used in atomic services since API version 11.
923
924**System capability**: SystemCapability.HiviewDFX.HiAppEvent
925
926**Parameters**
927
928| Name    | Type                   | Mandatory| Description         |
929| --------- | ----------------------- | ---- | ----------    |
930| name      | string                  | Yes  | Key of a user property. The value is string that contains a maximum of 256 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign ($). It must not start with a digit.|
931
932**Return value**
933
934| Type   | Description                            |
935| ------ | -------------------------------- |
936| string | Value of a user property. If no user ID is found, an empty string is returned.|
937
938**Error codes**
939
940| ID| Error Message         |
941| ------- | ----------------- |
942| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
943
944**Example**
945
946```ts
947import { hilog } from '@kit.PerformanceAnalysisKit';
948
949hiAppEvent.setUserProperty('key', 'value');
950try {
951  let value: string = hiAppEvent.getUserProperty('key');
952  hilog.info(0x0000, 'hiAppEvent', `getUserProperty event was successful, userProperty=${value}`);
953} catch (error) {
954  hilog.error(0x0000, 'hiAppEvent', `failed to getUserProperty event, code=${error.code}`);
955}
956```
957
958
959## hiAppEvent.clearData
960
961clearData(): void
962
963Clears local logging data of the application.
964
965**Atomic service API**: This API can be used in atomic services since API version 11.
966
967**System capability**: SystemCapability.HiviewDFX.HiAppEvent
968
969**Example**
970
971```ts
972hiAppEvent.clearData();
973```
974
975
976## hiAppEvent.configure
977
978configure(config: ConfigOption): void
979
980Configures the application event logging function, such as setting the logging switch and directory storage quota.
981
982**Atomic service API**: This API can be used in atomic services since API version 11.
983
984**System capability**: SystemCapability.HiviewDFX.HiAppEvent
985
986**Parameters**
987
988| Name| Type                         | Mandatory| Description                    |
989| ------ | ----------------------------- | ---- | ------------------------ |
990| config | [ConfigOption](#configoption) | Yes  | Configuration items for application event logging.|
991
992**Error codes**
993
994For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
995
996| ID| Error Message                        |
997| -------- | -------------------------------- |
998| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
999| 11103001 | Invalid max storage quota value. Possible caused by incorrectly formatted. |
1000
1001**Example**
1002
1003```ts
1004// Disable the event logging function.
1005let config1: hiAppEvent.ConfigOption = {
1006  disable: true,
1007};
1008hiAppEvent.configure(config1);
1009
1010// Set the maximum size of the file storage directory to 100 MB.
1011let config2: hiAppEvent.ConfigOption = {
1012  maxStorage: '100M',
1013};
1014hiAppEvent.configure(config2);
1015```
1016
1017
1018## ConfigOption
1019
1020Provides configuration options for application event logging.
1021
1022**Atomic service API**: This API can be used in atomic services since API version 11.
1023
1024**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1025
1026| Name      | Type   | Read Only| Optional| Description                                                        |
1027| ---------- | ------- | ---- | ---- | ------------------------------------------------------------ |
1028| disable    | boolean | No| Yes  | Whether to enable the event logging function. The default value is **false**. If this parameter is set to **true**, the logging function is disabled. Otherwise, the logging function is enabled.|
1029| maxStorage | string  | No| Yes  | Quota for the directory that stores event logging files. The default value is **10M**. It is recommended that the quota be less than or equal to 10 MB. Otherwise, the API efficiency may be affected.<br>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.<br>The quota value must meet the following requirements:<br>- The quota value consists of only digits and a unit (which can be one of [b\|k\|kb\|m\|mb\|g\|gb\|t\|tb], which are case insensitive.)<br>- The quota value must start with a digit. You can determine whether to pass the unit. If the unit is left empty, **b** (that is, byte) is used by default.|
1030
1031
1032## Processor<sup>11+</sup>
1033
1034Defines a data processor for reporting and managing events. You can customize processor configurations as required.
1035
1036**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1037
1038| Name               | Type                    | Read Only| Optional| Description                                                                                                       |
1039| ------------------- | ----------------------- | ---- | ---- | ---------------------------------------------------------------------------------------------------------- |
1040| name                | string                  | No| No  | Name of a data processor. The value is string that contains a maximum of 256 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign ($). It must not start with a digit.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                                                                          |
1041| debugMode           | boolean                 | No| Yes  | Whether to enable the debug mode. The default value is **false**. The value **true** means to enable the debugging mode, and the value **false** means the opposite.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                   |
1042| routeInfo           | string                  | No| Yes  | Server location information. It is left empty by default. The length of the input string cannot exceed 8 KB. If the length exceeds 8 KB, the default value is used.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                                                                  |
1043| appId               | string                  | No| Yes  | Application ID. It is left empty by default. The length of the input string cannot exceed 8 KB. If the length exceeds 8 KB, the default value is used.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.|
1044| onStartReport       | boolean                 | No| Yes  | Whether to report an event when the data processor starts. The default value is **false**. The value **true** means to report events, and the value **false** means the opposite.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                  |
1045| onBackgroundReport  | boolean                 | No| Yes  | Whether to report an event when an application switches to the background. The default value is **false**. The value **true** means to report events, and the value **false** means the opposite.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                |
1046| periodReport        | number                  | No| Yes  | Interval for event reporting, in seconds. The input value must be greater than or equal to **0**. If the input value is less than **0**, the default value **0** is used and periodic reporting is not performed.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                               |
1047| batchReport         | number                  | No| Yes  | Event reporting threshold. When the number of events reaches the threshold, an event is reported. The value must be greater than **0** and less than **1000**. If the value is not within the range, the default value **0** is used and no events are reported.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                        |
1048| userIds             | string[]                | No| Yes  | Name array of user IDs that can be reported by the data processor. **name** corresponds to the **name** parameter of the [setUserId](#hiappeventsetuserid11) API. The default value is an empty array.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.   |
1049| userProperties      | string[]                | No| Yes  | Name array of user properties that can be reported by the data processor. **name** corresponds to the **name** parameter of the [setUserProperty](#hiappeventsetuserproperty11) API. The default value is an empty array.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.  |
1050| eventConfigs        | [AppEventReportConfig](#appeventreportconfig11)[]  | No| Yes  | Event description configuration array that can be reported by the data processor. The default value is an empty array.<br>**Atomic service API**: This parameter can be used in atomic services since API version 11.                                                                                |
1051| configId<sup>12+</sup> | number | No| Yes| Configuration ID for data processor. The input value must be greater than or equal to **0**. If the input value is less than **0**, the default value 0 is used. If the input value is greater than 0, the value uniquely identifies a data processor with its name.<br>**Atomic service API**: This parameter can be used in atomic services since API version 12.|
1052| customConfigs<sup>12+</sup> | Record\<string, string> | No| Yes| Custom extended parameters. If the input parameter name and value do not meet the specifications, extended parameters are not configured by default. The specifications are as follows:<br>- A parameter name is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign (`$`). It must start with a letter or dollar sign (`$`) and end with a digit or letter.<br>- A parameter value is a string contains a maximum of 1024 characters.<br>- The number of parameters must be less than 32.<br>**Atomic service API**: This parameter can be used in atomic services since API version 12.|
1053| configName<sup>20+</sup>    | string                  | No| Yes  | <!--RP4-->Name of the data processor configuration, which can be loaded from the configuration file. By default, this parameter is left empty. It can contain only letters, digits, underscores (_), and dollar signs ($). It cannot start with a digit and cannot exceed 256 characters.<br>**Atomic service API**: This parameter can be used in atomic services since API version 20.<!--RP4End-->|
1054
1055
1056## AppEventReportConfig<sup>11+</sup>
1057
1058Defines the event configuration for the data processor to report.
1059
1060**Atomic service API**: This API can be used in atomic services since API version 11.
1061
1062**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1063
1064| Name        | Type   | Read Only| Optional| Description                                                         |
1065| ----------- | ------- | ---- | ---- | ------------------------------------------------------------ |
1066| domain      | string  | No| Yes  | Event domain. The value is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscore (\_). It must start with a letter and cannot end with an underscore (\_). The default value is an empty string.|
1067| name        | string  | No| Yes  | Event name. The value is string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), underscore (_), and dollar sign (`$`). It must start with a letter or dollar sign (`$`) and end with a digit or letter. The default value is an empty string.|
1068| isRealTime  | boolean | No| Yes  | Whether to report events in real time. The value **true** indicates that events are reported in real time, and the value **false** indicates the opposite. The default value is **false**.|
1069
1070
1071## ParamType<sup>12+</sup>
1072
1073type ParamType = number | string | boolean | Array&lt;string&gt;
1074
1075Enumerates the types of custom event parameter values.
1076
1077**Atomic service API**: This API can be used in atomic services since API version 12.
1078
1079**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1080
1081| Type                      | Description               |
1082|--------------------------|-------------------|
1083| number                   | Number.        |
1084| string                   | String.       |
1085| boolean                  | The value is true or false.       |
1086| Array&lt;string&gt;      | The value is an array of strings.  |
1087
1088
1089## EventType
1090
1091Enumerates event types.
1092
1093**Atomic service API**: This API can be used in atomic services since API version 11.
1094
1095**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1096
1097| Name     | Value  | Description          |
1098| --------- | ---- | -------------- |
1099| FAULT     | 1    | Fault event.|
1100| STATISTIC | 2    | Statistical event.|
1101| SECURITY  | 3    | Security event.|
1102| BEHAVIOR  | 4    | Behavior event.|
1103
1104
1105## hiAppEvent.domain<sup>11+</sup>
1106
1107Provides domain name constants.
1108
1109**Atomic service API**: This API can be used in atomic services since API version 11.
1110
1111**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1112
1113| Name| Type  | Read Only  | Description      |
1114| ---  | ------ | ------ | ---------- |
1115| OS   | string | Yes| System domain.|
1116
1117
1118## hiAppEvent.event
1119
1120Provides event name constants, including system event name constants and application event name constants. The application event name constants are optional custom event names reserved when you call [Write](#hiappeventwrite-1) for application event logging.
1121
1122**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1123
1124| Name                     | Type  | Read Only  | Description                |
1125| ------------------------- | ------ | ------ | -------------------- |
1126| USER_LOGIN                | string | Yes| User login event. This is a reserved application event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
1127| USER_LOGOUT               | string | Yes| User logout event. This is a reserved application event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
1128| DISTRIBUTED_SERVICE_START | string | Yes| Distributed service startup event. This is a reserved application event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1129| APP_CRASH<sup>11+</sup>   | string | Yes| Application crash event. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
1130| APP_FREEZE<sup>11+</sup>  | string | Yes| Application freeze event. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
1131| APP_LAUNCH<sup>12+</sup>  | string | Yes| Event indicating the application launch duration. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
1132| SCROLL_JANK<sup>12+</sup> | string | Yes| Event indicating frame loss during swiping. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
1133| CPU_USAGE_HIGH<sup>12+</sup> | string | Yes| Event indicating a high CPU usage. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1134| BATTERY_USAGE<sup>12+</sup> | string | Yes| Event indicating battery usage statistics. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1135| RESOURCE_OVERLIMIT<sup>12+</sup> | string | Yes| Event indicating an application resource leakage. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1136| ADDRESS_SANITIZER<sup>12+</sup> | string | Yes| Application address sanitizer event. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1137| MAIN_THREAD_JANK<sup>12+</sup> | string | Yes| Main thread jank event. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1138| APP_KILLED<sup>20+</sup> | string | Yes| Application killing event. This is a system event name constant.<br>**Atomic service API**: This API can be used in atomic services since API version 20.|
1139
1140
1141## hiAppEvent.param
1142
1143Provides parameter name constants.
1144
1145**Atomic service API**: This API can be used in atomic services since API version 11.
1146
1147**System capability**: SystemCapability.HiviewDFX.HiAppEvent
1148
1149| Name                           | Type  | Read Only  | Description              |
1150| ------------------------------- | ------ | ------ | ------------------ |
1151| USER_ID                         | string | Yes| Custom user ID.    |
1152| DISTRIBUTED_SERVICE_NAME        | string | Yes| Distributed service name.  |
1153| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes| Distributed service instance ID.|
1154