1# @ohos.hiviewdfx.hiAppEvent (HiAppEvent)
2
3The **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.
4
5> **NOTE**
6>
7> 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.
8
9
10## Modules to Import
11
12```ts
13import { hiAppEvent } from '@kit.PerformanceAnalysisKit';
14```
15
16## hiAppEvent.addProcessor<sup>11+</sup>
17
18addProcessor(processor: Processor): number
19
20Adds a data processor for migrating events to the cloud. The implementation of data processors can be preset in the device. You can set attributes of the data processor based on its constraints.
21
22The configuration information of **Processor** must be provided by the data processor. Yet, as no data processor is preset in the device for interaction for the moment, migrating events to the cloud is unavailable.
23
24**Atomic service API**: This API can be used in atomic services since API version 11.
25
26**System capability**: SystemCapability.HiviewDFX.HiAppEvent
27
28**Parameters**
29
30| Name    | Type       | Mandatory | Description             |
31| ---------  | ---------- | ---- | -------------    |
32| processor  | [Processor](#processor11)  | Yes  | Data processor.|
33
34**Return value**
35
36| Type   | Description                  |
37| ------ | ---------------------- |
38| number | ID of the data processor to be added. If the operation fails, **-1** is returned. If the operation is successful, a value greater than **0** is returned. |
39
40**Error codes**
41
42| ID | Error Message         |
43| ------- | ----------------- |
44| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
45
46**Example**
47
48```ts
49import { hilog } from '@kit.PerformanceAnalysisKit';
50
51try {
52    let processor: hiAppEvent.Processor = {
53      name: 'analytics_demo'
54    };
55    let id: number = hiAppEvent.addProcessor(processor);
56    hilog.info(0x0000, 'hiAppEvent', `addProcessor event was successful, id=${id}`);
57} catch (error) {
58    hilog.error(0x0000, 'hiAppEvent', `failed to addProcessor event, code=${error.code}`);
59}
60```
61
62## Processor<sup>11+</sup>
63
64Defines a data processor for reporting events.
65
66**System capability**: SystemCapability.HiviewDFX.HiAppEvent
67
68| Name               | Type                    | Mandatory | Description                                                                                                       |
69| ------------------- | ----------------------- | ---- | ---------------------------------------------------------------------------------------------------------- |
70| name                | string                  | Yes  | 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 API can be used in atomic services since API version 11.                                                                                          |
71| debugMode           | boolean                 | No  | 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 API can be used in atomic services since API version 11.                                   |
72| routeInfo           | string                  | No  | 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 API can be used in atomic services since API version 11.                                                                                  |
73| appId               | string                  | No  | 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 API can be used in atomic services since API version 11. |
74| onStartReport       | boolean                 | No  | 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 API can be used in atomic services since API version 11.                                  |
75| onBackgroundReport  | boolean                 | No  | 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 API can be used in atomic services since API version 11.                                |
76| periodReport        | number                  | No  | 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 API can be used in atomic services since API version 11.                                               |
77| batchReport         | number                  | No  | 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 API can be used in atomic services since API version 11.                        |
78| userIds             | string[]                | No  | Name array of user IDs that can be reported by the data processor. **name** corresponds to the **name** parameter of the [setUserId](#hiappeventsetuserid11) API.<br>**Atomic service API**: This API can be used in atomic services since API version 11.   |
79| userProperties      | string[]                | No  | Name array of user properties that can be reported by the data processor. **name** corresponds to the **name** parameter of the [setUserProperty](#hiappeventsetuserproperty11) API.<br>**Atomic service API**: This API can be used in atomic services since API version 11.  |
80| eventConfigs        | [AppEventReportConfig](#appeventreportconfig11)[]  | No  | Array of events that can be reported by the data processor.<br>**Atomic service API**: This API can be used in atomic services since API version 11.                                                                                |
81| configId<sup>12+</sup> | number | No | 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 API can be used in atomic services since API version 12. |
82| customConfigs<sup>12+</sup> | Record\<string, string> | No | 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 API can be used in atomic services since API version 12. |
83
84## AppEventReportConfig<sup>11+</sup>
85
86Description of events that can be reported by the data processor.
87
88**Atomic service API**: This API can be used in atomic services since API version 11.
89
90**System capability**: SystemCapability.HiviewDFX.HiAppEvent
91
92| Name        | Type   | Mandatory | Description                                                         |
93| ----------- | ------- | ---- | ------------------------------------------------------------ |
94| domain      | string  | 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 (_). |
95| name        | string  | 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. |
96| isRealTime  | boolean | No  | Whether to report events in real time. The value **true** means to report events, and the value **false** means the opposite. |
97
98## hiAppEvent.removeProcessor<sup>11+</sup>
99
100removeProcessor(id: number): void
101
102Removes a data processor.
103
104**Atomic service API**: This API can be used in atomic services since API version 11.
105
106**System capability**: SystemCapability.HiviewDFX.HiAppEvent
107
108**Parameters**
109
110| Name | Type   | Mandatory | Description                        |
111| ------| ------- | ---- | --------------------------- |
112| id    | number  | Yes  | ID of a data processor. The value must be greater than **0**.|
113
114**Error codes**
115
116| ID | Error Message         |
117| ------- | ----------------- |
118| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
119
120**Example**
121
122```ts
123import { hilog } from '@kit.PerformanceAnalysisKit';
124
125try {
126    let processor: hiAppEvent.Processor = {
127      name: 'analytics_demo'
128    };
129    let id: number = hiAppEvent.addProcessor(processor);
130    hiAppEvent.removeProcessor(id);
131} catch (error) {
132    hilog.error(0x0000, 'hiAppEvent', `failed to removeProcessor event, code=${error.code}`);
133}
134```
135
136## hiAppEvent.write
137
138write(info: AppEventInfo, callback: AsyncCallback&lt;void&gt;): void
139
140Writes events to the event file of the current day through **AppEventInfo** objects. This API uses an asynchronous callback to return the result.
141
142**Atomic service API**: This API can be used in atomic services since API version 11.
143
144**System capability**: SystemCapability.HiviewDFX.HiAppEvent
145
146**Parameters**
147
148| Name  | Type                          | Mandatory | Description          |
149| -------- | ------------------------------ | ---- | -------------- |
150| info     | [AppEventInfo](#appeventinfo) | Yes  | Application event object. |
151| callback | AsyncCallback&lt;void&gt;      | Yes  | Callback used to return the result. |
152
153**Error codes**
154
155For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
156
157| ID | Error Message                                     |
158| -------- | --------------------------------------------- |
159| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
160| 11100001 | Function is disabled.                         |
161| 11101001 | Invalid event domain.                         |
162| 11101002 | Invalid event name.                           |
163| 11101003 | Invalid number of event parameters.           |
164| 11101004 | Invalid string length of the event parameter. |
165| 11101005 | Invalid event parameter name.                 |
166| 11101006 | Invalid array length of the event parameter.  |
167
168**Example**
169
170```ts
171import { BusinessError } from '@kit.BasicServicesKit';
172import { hilog } from '@kit.PerformanceAnalysisKit';
173
174let eventParams: Record<string, number | string> = {
175  "int_data": 100,
176  "str_data": "strValue",
177};
178hiAppEvent.write({
179  domain: "test_domain",
180  name: "test_event",
181  eventType: hiAppEvent.EventType.FAULT,
182  params: eventParams,
183}, (err: BusinessError) => {
184  if (err) {
185    hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
186    return;
187  }
188  hilog.info(0x0000, 'hiAppEvent', `success to write event`);
189});
190```
191
192## hiAppEvent.write
193
194write(info: AppEventInfo): Promise&lt;void&gt;
195
196Writes events to the event file of the current day through **AppEventInfo** objects. This API uses a promise to return the result.
197
198**Atomic service API**: This API can be used in atomic services since API version 11.
199
200**System capability**: SystemCapability.HiviewDFX.HiAppEvent
201
202**Parameters**
203
204| Name | Type                          | Mandatory | Description          |
205| ------ | ------------------------------ | ---- | -------------- |
206| info   | [AppEventInfo](#appeventinfo) | Yes  | Application event object. |
207
208**Return value**
209
210| Type               | Description         |
211| ------------------- | ------------- |
212| Promise&lt;void&gt; | Promise used to return the result. |
213
214**Error codes**
215
216For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
217
218| ID | Error Message                                     |
219| -------- | --------------------------------------------- |
220| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
221| 11100001 | Function is disabled.                         |
222| 11101001 | Invalid event domain.                         |
223| 11101002 | Invalid event name.                           |
224| 11101003 | Invalid number of event parameters.           |
225| 11101004 | Invalid string length of the event parameter. |
226| 11101005 | Invalid event parameter name.                 |
227| 11101006 | Invalid array length of the event parameter.  |
228
229**Example**
230
231```ts
232import { BusinessError } from '@kit.BasicServicesKit';
233import { hilog } from '@kit.PerformanceAnalysisKit';
234
235let eventParams: Record<string, number | string> = {
236  "int_data": 100,
237  "str_data": "strValue",
238};
239hiAppEvent.write({
240  domain: "test_domain",
241  name: "test_event",
242  eventType: hiAppEvent.EventType.FAULT,
243  params: eventParams,
244}).then(() => {
245  hilog.info(0x0000, 'hiAppEvent', `success to write event`);
246}).catch((err: BusinessError) => {
247  hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
248});
249```
250
251## AppEventInfo
252
253Defines parameters for an **AppEventInfo** object.
254
255**Atomic service API**: This API can be used in atomic services since API version 11.
256
257**System capability**: SystemCapability.HiviewDFX.HiAppEvent
258
259| Name     | Type                   | Mandatory | Description                                                        |
260| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
261| domain    | string                  | Yes  | 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 (_). |
262| name      | string                  | 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.|
263| eventType | [EventType](#eventtype) | Yes  | Event type.                                                  |
264| params    | object                  | Yes  | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- A parameter name is a string that contains a maximum of 16 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 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.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
265
266## hiAppEvent.setEventParam<sup>12+</sup>
267
268setEventParam(params: Record&lt;string, ParamType&gt;, domain: string, name?: string): Promise&lt;void&gt;
269
270Method for setting custom event parameters. This API uses a promise to return the result. In the same lifecycle, you can associate system events with application events by event domain and event name. Only crash and freeze events are supported.
271
272**Atomic service API**: This API can be used in atomic services since API version 12.
273
274**System capability**: SystemCapability.HiviewDFX.HiAppEvent
275
276**Parameters**
277
278| Name | Type                          | Mandatory | Description          |
279| ------ | ------------------------------ | ---- | -------------- |
280| params | Record&lt;string, [ParamType](#paramtype12)&gt; | Yes | Custom parameter object. The parameter names and parameter values are defined as follows:<br>- A parameter name is a string that contains a maximum of 16 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. |
281| domain | string                        | Yes | Event domain. The event domain can be associated with application events and system events (hiAppEvent.domain.OS). |
282| name   | string                        | No | Event name. The default value is an empty string, which indicates all event names in the associated event domain. The event name can be associated with application events and system events. System events can be associated only with crash events (hiAppEvent.event.APP_CRASH) and freeze events (hiAppEvent.event.APP_FREEZE). |
283
284**Return value**
285
286| Type               | Description         |
287| ------------------- | ------------- |
288| Promise&lt;void&gt; | Promise used to return the result. |
289
290**Error codes**
291
292For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
293
294| ID | Error Message                                     |
295| -------- | --------------------------------------------- |
296| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
297| 11101007 | The number of parameter keys exceeds the limit. |
298
299**Example**
300
301```ts
302import { BusinessError } from '@kit.BasicServicesKit';
303import { hilog } from '@kit.PerformanceAnalysisKit';
304
305let params: Record<string, hiAppEvent.ParamType> = {
306  "int_data": 100,
307  "str_data": "strValue",
308};
309// Add custom parameters to the application event.
310hiAppEvent.setEventParam(params, "test_domain", "test_event").then(() => {
311  hilog.info(0x0000, 'hiAppEvent', `success to set svent param`);
312}).catch((err: BusinessError) => {
313  hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
314});
315```
316
317## ParamType<sup>12+</sup>
318
319type ParamType = number | string | boolean | Array&lt;string&gt;
320
321Type of a custom event parameter value.
322
323**Atomic service API**: This API can be used in atomic services since API version 12.
324
325**System capability**: SystemCapability.HiviewDFX.HiAppEvent
326
327| Type                      | Description               |
328|--------------------------|-------------------|
329| number                   | Number.        |
330| string                   | String.       |
331| boolean                  | The value is true or false.       |
332| Array&lt;string&gt;      | The value is an array of strings.  |
333
334## hiAppEvent.configure
335
336configure(config: ConfigOption): void
337
338Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files.
339
340**Atomic service API**: This API can be used in atomic services since API version 11.
341
342**System capability**: SystemCapability.HiviewDFX.HiAppEvent
343
344**Parameters**
345
346| Name | Type                         | Mandatory | Description                    |
347| ------ | ----------------------------- | ---- | ------------------------ |
348| config | [ConfigOption](#configoption) | Yes  | Configuration items for application event logging. |
349
350**Error codes**
351
352For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
353
354| ID | Error Message                        |
355| -------- | -------------------------------- |
356| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
357| 11103001 | Invalid max storage quota value. |
358
359**Example**
360
361```ts
362// Disable the event logging function.
363let config1: hiAppEvent.ConfigOption = {
364  disable: true,
365};
366hiAppEvent.configure(config1);
367
368// Set the maximum size of the file storage directory to 100 MB.
369let config2: hiAppEvent.ConfigOption = {
370  maxStorage: '100M',
371};
372hiAppEvent.configure(config2);
373```
374
375## ConfigOption
376
377Provides configuration options for application event logging.
378
379**Atomic service API**: This API can be used in atomic services since API version 11.
380
381**System capability**: SystemCapability.HiviewDFX.HiAppEvent
382
383| Name      | Type   | Mandatory | Description                                                        |
384| ---------- | ------- | ---- | ------------------------------------------------------------ |
385| disable    | boolean | No  | Whether 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. |
386| maxStorage | string  | No  | Quota for the directory that stores event logging files. The default value is **10M**.<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. |
387
388## hiAppEvent.setUserId<sup>11+</sup>
389
390setUserId(name: string, value: string): void
391
392Sets a user ID.
393
394**Atomic service API**: This API can be used in atomic services since API version 11.
395
396**System capability**: SystemCapability.HiviewDFX.HiAppEvent
397
398**Parameters**
399
400| Name    | Type                     | Mandatory | Description          |
401| --------- | ------------------------- | ---- | -------------  |
402| 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.  |
403| 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. |
404
405**Error codes**
406
407| ID | Error Message         |
408| ------- | ----------------- |
409| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
410
411**Example**
412
413```ts
414import { hilog } from '@kit.PerformanceAnalysisKit';
415
416try {
417  hiAppEvent.setUserId('key', 'value');
418} catch (error) {
419  hilog.error(0x0000, 'hiAppEvent', `failed to setUserId event, code=${error.code}`);
420}
421```
422
423## hiAppEvent.getUserId<sup>11+</sup>
424
425getUserId(name: string): string
426
427Obtains the value set by **setUserId**.
428
429**Atomic service API**: This API can be used in atomic services since API version 11.
430
431**System capability**: SystemCapability.HiviewDFX.HiAppEvent
432
433**Parameters**
434
435| Name    | Type                   | Mandatory | Description        |
436| --------- | ----------------------- | ---- | ----------  |
437| 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.|
438
439**Return value**
440
441| Type   | Description                           |
442| ------ | ------------------------------- |
443| string | Value of a user ID. If no user ID is found, an empty string is returned. |
444
445**Error codes**
446
447| ID | Error Message         |
448| ------- | ----------------- |
449| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
450
451**Example**
452
453```ts
454import { hilog } from '@kit.PerformanceAnalysisKit';
455
456hiAppEvent.setUserId('key', 'value');
457try {
458  let value: string = hiAppEvent.getUserId('key');
459  hilog.info(0x0000, 'hiAppEvent', `getUserId event was successful, userId=${value}`);
460} catch (error) {
461  hilog.error(0x0000, 'hiAppEvent', `failed to getUserId event, code=${error.code}`);
462}
463```
464
465## hiAppEvent.setUserProperty<sup>11+</sup>
466
467setUserProperty(name: string, value: string): void
468
469Sets user properties.
470
471**Atomic service API**: This API can be used in atomic services since API version 11.
472
473**System capability**: SystemCapability.HiviewDFX.HiAppEvent
474
475**Parameters**
476
477| Name    | Type                     | Mandatory | Description          |
478| --------- | ------------------------- | ---- | -------------- |
479| 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. |
480| value     | string                    | Yes  | Value of a user property. It is a string that contains a maximum of 1024 characters. If the value is **null**, **undefine**, or **empty**, the user property is cleared. |
481
482**Error codes**
483
484| ID | Error Message         |
485| ------- | ----------------- |
486| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
487
488**Example**
489
490```ts
491import { hilog } from '@kit.PerformanceAnalysisKit';
492
493try {
494  hiAppEvent.setUserProperty('key', 'value');
495} catch (error) {
496  hilog.error(0x0000, 'hiAppEvent', `failed to setUserProperty event, code=${error.code}`);
497}
498```
499
500## hiAppEvent.getUserProperty<sup>11+</sup>
501
502getUserProperty(name: string): string
503
504Obtains the value set by **setUserProperty**.
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**Parameters**
511
512| Name    | Type                   | Mandatory | Description         |
513| --------- | ----------------------- | ---- | ----------    |
514| 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.|
515
516**Return value**
517
518| Type   | Description                            |
519| ------ | -------------------------------- |
520| string | Value of a user property. If no user ID is found, an empty string is returned. |
521
522**Error codes**
523
524| ID | Error Message         |
525| ------- | ----------------- |
526| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
527
528**Example**
529
530```ts
531import { hilog } from '@kit.PerformanceAnalysisKit';
532
533hiAppEvent.setUserProperty('key', 'value');
534try {
535  let value: string = hiAppEvent.getUserProperty('key');
536  hilog.info(0x0000, 'hiAppEvent', `getUserProperty event was successful, userProperty=${value}`);
537} catch (error) {
538  hilog.error(0x0000, 'hiAppEvent', `failed to getUserProperty event, code=${error.code}`);
539}
540```
541
542## hiAppEvent.addWatcher
543
544addWatcher(watcher: Watcher): AppEventPackageHolder
545
546Adds a watcher to subscribe to application events.
547
548**Atomic service API**: This API can be used in atomic services since API version 11.
549
550**System capability**: SystemCapability.HiviewDFX.HiAppEvent
551
552**Parameters**
553
554| Name | Type                | Mandatory | Description            |
555| ------- | -------------------- | ---- | ---------------- |
556| watcher | [Watcher](#watcher) | Yes  | Watcher for application events. |
557
558**Return value**
559
560| Type                                            | Description                                |
561| ------------------------------------------------ | ------------------------------------ |
562| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** will be returned. |
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| 11102001 | Invalid watcher name.           |
572| 11102002 | Invalid filtering event domain. |
573| 11102003 | Invalid row value.              |
574| 11102004 | Invalid size value.             |
575| 11102005 | Invalid timeout value.          |
576
577**Example**
578
579```ts
580import { hilog } from '@kit.PerformanceAnalysisKit';
581
582// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
583hiAppEvent.addWatcher({
584  name: "watcher1",
585  appEventFilters: [
586    {
587      domain: "test_domain",
588      eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
589    }
590  ],
591  triggerCondition: {
592    row: 10,
593    size: 1000,
594    timeOut: 1
595  },
596  onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => {
597    if (holder == null) {
598      hilog.error(0x0000, 'hiAppEvent', "holder is null");
599      return;
600    }
601    hilog.info(0x0000, 'hiAppEvent', `curRow=${curRow}, curSize=${curSize}`);
602    let eventPkg: hiAppEvent.AppEventPackage | null = null;
603    while ((eventPkg = holder.takeNext()) != null) {
604      hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`);
605      hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`);
606      hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`);
607      for (const eventInfo of eventPkg.data) {
608        hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`);
609      }
610    }
611  }
612});
613
614// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
615let holder = hiAppEvent.addWatcher({
616  name: "watcher2",
617});
618if (holder != null) {
619  let eventPkg: hiAppEvent.AppEventPackage | null = null;
620  while ((eventPkg = holder.takeNext()) != null) {
621    hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`);
622    hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`);
623    hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`);
624    for (const eventInfo of eventPkg.data) {
625      hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`);
626    }
627  }
628}
629
630// 3. You can have the watcher processed the subscription event in the onReceive function.
631hiAppEvent.addWatcher({
632  name: "watcher3",
633  appEventFilters: [
634    {
635      domain: "test_domain",
636      eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
637    }
638  ],
639  onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => {
640    hilog.info(0x0000, 'hiAppEvent', `domain=${domain}`);
641    for (const eventGroup of appEventGroups) {
642      hilog.info(0x0000, 'hiAppEvent', `eventName=${eventGroup.name}`);
643      for (const eventInfo of eventGroup.appEventInfos) {
644        hilog.info(0x0000, 'hiAppEvent', `event=${JSON.stringify(eventInfo)}`, );
645      }
646    }
647  }
648});
649```
650
651## hiAppEvent.removeWatcher
652
653removeWatcher(watcher: Watcher): void
654
655Removes a watcher to unsubscribe from application events.
656
657**Atomic service API**: This API can be used in atomic services since API version 11.
658
659**System capability**: SystemCapability.HiviewDFX.HiAppEvent
660
661**Parameters**
662
663| Name | Type                | Mandatory | Description            |
664| ------- | -------------------- | ---- | ---------------- |
665| watcher | [Watcher](#watcher) | Yes  | Watcher for application events. |
666
667**Error codes**
668
669For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
670
671| ID | Error Message             |
672| -------- | --------------------- |
673| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
674| 11102001 | Invalid watcher name. |
675
676**Example**
677
678```ts
679// 1. Define a watcher for application events.
680let watcher: hiAppEvent.Watcher = {
681  name: "watcher1",
682}
683
684// 2. Add the watcher to subscribe to application events.
685hiAppEvent.addWatcher(watcher);
686
687// 3. Remove the watcher to unsubscribe from application events.
688hiAppEvent.removeWatcher(watcher);
689```
690
691## Watcher
692
693Defines parameters for a **Watcher** object.
694
695**Atomic service API**: This API can be used in atomic services since API version 11.
696
697**System capability**: SystemCapability.HiviewDFX.HiAppEvent
698
699| Name            | Type                                                        | Mandatory | Description                                                        |
700| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
701| name             | string                                                       | Yes  | Unique name of a watcher.                            |
702| triggerCondition | [TriggerCondition](#triggercondition)                        | No  | Subscription callback triggering condition. This parameter takes effect only when it is passed together with **onTrigger**.          |
703| appEventFilters  | [AppEventFilter](#appeventfilter)[]                          | No  | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered.              |
704| onTrigger        | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void | No  | 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. |
705| onReceive<sup>11+</sup>        | (domain: string, appEventGroups: Array<[AppEventGroup](#appeventgroup11)>) => void | No | 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. |
706
707## TriggerCondition
708
709Defines callback triggering conditions. A callback is triggered when any specified condition is met.
710
711**Atomic service API**: This API can be used in atomic services since API version 11.
712
713**System capability**: SystemCapability.HiviewDFX.HiAppEvent
714
715| Name   | Type  | Mandatory | Description                                  |
716| ------- | ------ | ---- | -------------------------------------- |
717| row     | number | No  | Number of events.            |
718| size    | number | No  | Event data size, in bytes. |
719| timeOut | number | No  | Timeout interval, in unit of 30s.   |
720
721## AppEventFilter
722
723Defines parameters for an **AppEventFilter** object.
724
725**Atomic service API**: This API can be used in atomic services since API version 11.
726
727**System capability**: SystemCapability.HiviewDFX.HiAppEvent
728
729| Name      | Type                     | Mandatory | Description                    |
730| ---------- | ------------------------- | ---- | ------------------------ |
731| domain     | string                    | Yes  | Event domain.    |
732| eventTypes | [EventType](#eventtype)[] | No  | Event types. |
733| names<sup>11+</sup>      | string[]                  | No  | Names of the events to be subscribed. |
734
735## AppEventPackageHolder
736
737Defines a subscription data holder for processing subscription events.
738
739### constructor
740
741constructor(watcherName: string)
742
743A constructor used to create a holder object for subscription data. It is associated with a **Watcher** object based on its name.
744
745**Atomic service API**: This API can be used in atomic services since API version 11.
746
747**System capability**: SystemCapability.HiviewDFX.HiAppEvent
748
749**Parameters**
750
751| Name | Type             | Mandatory | Description                    |
752| ------ | ----------------- | ---- | ------------------------ |
753| watcherName | string | Yes  | Watcher name. |
754
755**Example**
756
757```ts
758let holder1: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher1");
759```
760
761### setSize
762
763setSize(size: number): void
764
765Sets the threshold for the data size of the application event package obtained each time.
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| size   | number | Yes  | Data size, in bytes. The value is greater than or equal to 0, otherwise, an exception is thrown. |
776
777**Error codes**
778
779For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
780
781| ID | Error Message           |
782| -------- | ------------------- |
783| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
784| 11104001 | Invalid size value. |
785
786**Example**
787
788```ts
789let holder2: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher2");
790holder2.setSize(1000);
791```
792
793### setRow<sup>12+</sup>
794
795setRow(size: number): void
796
797Sets the number of data records obtained from the application event package each time. When **setRow()** and **setSize()** are called at the same time, only **setRow()** takes effect.
798
799**Atomic service API**: This API can be used in atomic services since API version 12.
800
801**System capability**: SystemCapability.HiviewDFX.HiAppEvent
802
803**Parameters**
804
805| Name | Type  | Mandatory | Description                                        |
806| ------ | ------ | ---- | -------------------------------------------- |
807| size   | number | Yes  | Number of application events. The value must be greater than 0, otherwise, an exception is thrown. |
808
809**Error codes**
810
811For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
812
813| ID | Error Message           |
814| -------- | ------------------- |
815| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
816| 11104001 | Invalid size value. |
817
818**Example**
819
820```ts
821let holder3: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher3");
822holder3.setRow(1000);
823```
824
825### takeNext
826
827takeNext(): AppEventPackage
828
829Extracts subscription event data based on the configured data size threshold or the number of application events. If all subscription event data has been extracted, **null** will be returned.
8301. When an application only calls **setSize()** , the subscription events are obtained based on the data size.
8312. When an application calls **setRow()**, the subscription events are obtained based on the **number** of **setRow()** regardless of whether **setSize()** is called.
8323. If neither **setSize()** nor **setRow()** is called, one subscription event is obtained by default.
833
834**Atomic service API**: This API can be used in atomic services since API version 11.
835
836**System capability**: SystemCapability.HiviewDFX.HiAppEvent
837
838**Return value**
839
840| Type                               | Description                                                  |
841| ----------------------------------- | ------------------------------------------------------ |
842| [AppEventPackage](#appeventpackage) | Event package object. If all subscription event data has been retrieved, **null** is returned. |
843
844**Example**
845
846```ts
847let holder4: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher4");
848let eventPkg = holder4.takeNext();
849```
850
851## AppEventPackage
852
853Defines parameters for an **AppEventPackage** object.
854
855**System capability**: SystemCapability.HiviewDFX.HiAppEvent
856
857| Name     | Type    | Mandatory | Description                          |
858| --------- | -------- | ---- | ------------------------------ |
859| packageId | number   | Yes  | 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.   |
860| row       | number   | Yes  | Number of events in the event package.<br>**Atomic service API**: This API can be used in atomic services since API version 11.            |
861| size      | number   | Yes  | Event size of the event package, in bytes.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
862| data      | string[] | Yes  | Event data in the event package.<br>**Atomic service API**: This API can be used in atomic services since API version 11.            |
863| appEventInfos<sup>12+</sup> | Array<[AppEventInfo](#appeventinfo)> | Yes  | Event object group.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
864
865## AppEventGroup<sup>11+</sup>
866
867Defines the event group returned by a subscription.
868
869**Atomic service API**: This API can be used in atomic services since API version 11.
870
871**System capability**: SystemCapability.HiviewDFX.HiAppEvent
872
873| Name         | Type                           | Mandatory | Description         |
874| ------------- | ------------------------------- | ---- | ------------- |
875| name          | string                          | Yes  | Event name.    |
876| appEventInfos | Array<[AppEventInfo](#appeventinfo)> | Yes  | Event object group. |
877
878## hiAppEvent.clearData
879
880clearData(): void
881
882Clears local application event logging data.
883
884**Atomic service API**: This API can be used in atomic services since API version 11.
885
886**System capability**: SystemCapability.HiviewDFX.HiAppEvent
887
888**Example**
889
890```ts
891hiAppEvent.clearData();
892```
893
894
895## EventType
896
897Enumerates event types.
898
899**Atomic service API**: This API can be used in atomic services since API version 11.
900
901**System capability**: SystemCapability.HiviewDFX.HiAppEvent
902
903| Name     | Value  | Description          |
904| --------- | ---- | -------------- |
905| FAULT     | 1    | Fault event. |
906| STATISTIC | 2    | Statistical event. |
907| SECURITY  | 3    | Security event. |
908| BEHAVIOR  | 4    | Behavior event. |
909
910
911## domain<sup>11+</sup>
912
913Defines the domain name of predefined events.
914
915**Atomic service API**: This API can be used in atomic services since API version 11.
916
917**System capability**: SystemCapability.HiviewDFX.HiAppEvent
918
919| Name | Type  | Description      |
920| ---  | ------ | ---------- |
921| OS   | string | System domain. |
922
923
924## event
925
926Defines the names of predefined events.
927
928**System capability**: SystemCapability.HiviewDFX.HiAppEvent
929
930| Name                     | Type  | Description                |
931| ------------------------- | ------ | -------------------- |
932| USER_LOGIN                | string | User login event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
933| USER_LOGOUT               | string | User logout event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
934| DISTRIBUTED_SERVICE_START | string | Distributed service startup event.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
935| APP_CRASH<sup>11+</sup>   | string | Application crash event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
936| APP_FREEZE<sup>11+</sup>  | string | Application freeze event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
937| APP_LAUNCH<sup>12+</sup>  | string | Event indicating the application launch duration.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
938| SCROLL_JANK<sup>12+</sup> | string | Event indicating frame loss during swiping.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
939| CPU_USAGE_HIGH<sup>12+</sup> | string | Event indicating a high CPU usage.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
940| BATTERY_USAGE<sup>12+</sup> | string | Event indicating battery usage statistics.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
941| RESOURCE_OVERLIMIT<sup>12+</sup> | string | Event indicating an application resource leakage.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
942| ADDRESS_SANITIZER<sup>12+</sup> | string | Address sanitizer event.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
943| MAIN_THREAD_JANK<sup>12+</sup> | string | Main thread jank event.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
944
945
946## param
947
948Defines the names of predefined event parameters.
949
950**Atomic service API**: This API can be used in atomic services since API version 11.
951
952**System capability**: SystemCapability.HiviewDFX.HiAppEvent
953
954| Name                           | Type  | Description              |
955| ------------------------------- | ------ | ------------------ |
956| USER_ID                         | string | Custom user ID.    |
957| DISTRIBUTED_SERVICE_NAME        | string | Distributed service name.  |
958| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID. |
959