1# @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
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 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 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. In system events, the fields contained in **params** are defined by system. For details about the fields, you can see the introduction to system events, for example, [Crash Event Overview](../../dfx/hiappevent-watcher-crash-events.md). For application events, you need to define the logging parameters. 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>- 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
270Sets 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 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.|
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.
615// For the crash event (hiAppEvent.event.APP_CRASH) and freeze event (hiAppEvent.event.APP_FREEZE) generated when the system exits abnormally, it takes some time for the system to capture maintenance and debugging logs. Typically, the capture is completed within 30s, in extreme cases, it takes about 2 minutes. If you want to manually process subscription events, you are advised to call takeNext() after the process starts.
616let holder = hiAppEvent.addWatcher({
617  name: "watcher2",
618});
619if (holder != null) {
620  let eventPkg: hiAppEvent.AppEventPackage | null = null;
621  while ((eventPkg = holder.takeNext()) != null) {
622    hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`);
623    hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`);
624    hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`);
625    for (const eventInfo of eventPkg.data) {
626      hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`);
627    }
628  }
629}
630
631// 3. You can have the watcher processed the subscription event in the onReceive function.
632hiAppEvent.addWatcher({
633  name: "watcher3",
634  appEventFilters: [
635    {
636      domain: "test_domain",
637      eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
638    }
639  ],
640  onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => {
641    hilog.info(0x0000, 'hiAppEvent', `domain=${domain}`);
642    for (const eventGroup of appEventGroups) {
643      hilog.info(0x0000, 'hiAppEvent', `eventName=${eventGroup.name}`);
644      for (const eventInfo of eventGroup.appEventInfos) {
645        hilog.info(0x0000, 'hiAppEvent', `event=${JSON.stringify(eventInfo)}`, );
646      }
647    }
648  }
649});
650```
651
652## hiAppEvent.removeWatcher
653
654removeWatcher(watcher: Watcher): void
655
656Removes a watcher to unsubscribe from application events.
657
658**Atomic service API**: This API can be used in atomic services since API version 11.
659
660**System capability**: SystemCapability.HiviewDFX.HiAppEvent
661
662**Parameters**
663
664| Name | Type                | Mandatory| Description            |
665| ------- | -------------------- | ---- | ---------------- |
666| watcher | [Watcher](#watcher) | Yes  | Watcher for application events.|
667
668**Error codes**
669
670For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
671
672| ID| Error Message             |
673| -------- | --------------------- |
674| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
675| 11102001 | Invalid watcher name. |
676
677**Example**
678
679```ts
680// 1. Define a watcher for application events.
681let watcher: hiAppEvent.Watcher = {
682  name: "watcher1",
683}
684
685// 2. Add the watcher to subscribe to application events.
686hiAppEvent.addWatcher(watcher);
687
688// 3. Remove the watcher to unsubscribe from application events.
689hiAppEvent.removeWatcher(watcher);
690```
691
692## Watcher
693
694Defines parameters for a **Watcher** object.
695
696**Atomic service API**: This API can be used in atomic services since API version 11.
697
698**System capability**: SystemCapability.HiviewDFX.HiAppEvent
699
700| Name            | Type                                                        | Mandatory| Description                                                        |
701| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
702| name             | string                                                       | Yes  | Unique name of a watcher.                            |
703| triggerCondition | [TriggerCondition](#triggercondition)                        | No  | Subscription callback triggering condition. This parameter takes effect only when it is passed together with **onTrigger**.          |
704| appEventFilters  | [AppEventFilter](#appeventfilter)[]                          | No  | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered.              |
705| 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.|
706| 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.|
707
708## TriggerCondition
709
710Defines callback triggering conditions. A callback is triggered when any specified condition is met.
711
712**Atomic service API**: This API can be used in atomic services since API version 11.
713
714**System capability**: SystemCapability.HiviewDFX.HiAppEvent
715
716| Name   | Type  | Mandatory| Description                                  |
717| ------- | ------ | ---- | -------------------------------------- |
718| row     | number | No  | 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.            |
719| size    | number | No  | 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.|
720| timeOut | number | No  | 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.   |
721
722## AppEventFilter
723
724Defines parameters for an **AppEventFilter** object.
725
726**Atomic service API**: This API can be used in atomic services since API version 11.
727
728**System capability**: SystemCapability.HiviewDFX.HiAppEvent
729
730| Name      | Type                     | Mandatory| Description                    |
731| ---------- | ------------------------- | ---- | ------------------------ |
732| domain     | string                    | Yes  | Event domain.    |
733| eventTypes | [EventType](#eventtype)[] | No  | Event types.|
734| names<sup>11+</sup>      | string[]                  | No  | Names of the events to be subscribed.|
735
736## AppEventPackageHolder
737
738Defines a subscription data holder for processing subscription events.
739
740### constructor
741
742constructor(watcherName: string)
743
744A constructor used to create a holder object for subscription data. It is associated with a **Watcher** object based on its name.
745
746**Atomic service API**: This API can be used in atomic services since API version 11.
747
748**System capability**: SystemCapability.HiviewDFX.HiAppEvent
749
750**Parameters**
751
752| Name| Type             | Mandatory| Description                    |
753| ------ | ----------------- | ---- | ------------------------ |
754| watcherName | string | Yes  | Watcher name.|
755
756**Example**
757
758```ts
759let holder1: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher1");
760```
761
762### setSize
763
764setSize(size: number): void
765
766Sets the threshold for the data size of the application event package obtained each time.
767
768**Atomic service API**: This API can be used in atomic services since API version 11.
769
770**System capability**: SystemCapability.HiviewDFX.HiAppEvent
771
772**Parameters**
773
774| Name| Type  | Mandatory| Description                                        |
775| ------ | ------ | ---- | -------------------------------------------- |
776| size   | number | Yes  | Data size, in bytes. The value is greater than or equal to 0, otherwise, an exception is thrown.|
777
778**Error codes**
779
780For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
781
782| ID| Error Message           |
783| -------- | ------------------- |
784| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
785| 11104001 | Invalid size value. |
786
787**Example**
788
789```ts
790let holder2: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher2");
791holder2.setSize(1000);
792```
793
794### setRow<sup>12+</sup>
795
796setRow(size: number): void
797
798Sets 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.
799
800**Atomic service API**: This API can be used in atomic services since API version 12.
801
802**System capability**: SystemCapability.HiviewDFX.HiAppEvent
803
804**Parameters**
805
806| Name| Type  | Mandatory| Description                                        |
807| ------ | ------ | ---- | -------------------------------------------- |
808| size   | number | Yes  | Number of application events. The value must be greater than 0, otherwise, an exception is thrown.|
809
810**Error codes**
811
812For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md).
813
814| ID| Error Message           |
815| -------- | ------------------- |
816| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
817| 11104001 | Invalid size value. |
818
819**Example**
820
821```ts
822let holder3: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher3");
823holder3.setRow(1000);
824```
825
826### takeNext
827
828takeNext(): AppEventPackage
829
830Extracts 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.
8311. When an application only calls **setSize()** , the subscription events are obtained based on the data size.
8322. When an application calls **setRow()**, the subscription events are obtained based on the **number** of **setRow()** regardless of whether **setSize()** is called.
8333. If neither **setSize()** nor **setRow()** is called, one subscription event is obtained by default.
834
835**Atomic service API**: This API can be used in atomic services since API version 11.
836
837**System capability**: SystemCapability.HiviewDFX.HiAppEvent
838
839**Return value**
840
841| Type                               | Description                                                  |
842| ----------------------------------- | ------------------------------------------------------ |
843| [AppEventPackage](#appeventpackage) | Event package object. If all subscription event data has been retrieved, **null** is returned.|
844
845**Example**
846
847```ts
848let holder4: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher4");
849let eventPkg = holder4.takeNext();
850```
851
852## AppEventPackage
853
854Defines parameters for an **AppEventPackage** object.
855
856**System capability**: SystemCapability.HiviewDFX.HiAppEvent
857
858| Name     | Type    | Mandatory| Description                          |
859| --------- | -------- | ---- | ------------------------------ |
860| 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.   |
861| 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.            |
862| 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.|
863| 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.            |
864| 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.|
865
866## AppEventGroup<sup>11+</sup>
867
868Defines the event group returned by a subscription.
869
870**Atomic service API**: This API can be used in atomic services since API version 11.
871
872**System capability**: SystemCapability.HiviewDFX.HiAppEvent
873
874| Name         | Type                           | Mandatory | Description         |
875| ------------- | ------------------------------- | ---- | ------------- |
876| name          | string                          | Yes  | Event name.    |
877| appEventInfos | Array<[AppEventInfo](#appeventinfo)> | Yes  | Event object group.|
878
879## hiAppEvent.clearData
880
881clearData(): void
882
883Clears local application event logging data.
884
885**Atomic service API**: This API can be used in atomic services since API version 11.
886
887**System capability**: SystemCapability.HiviewDFX.HiAppEvent
888
889**Example**
890
891```ts
892hiAppEvent.clearData();
893```
894
895
896## EventType
897
898Enumerates event types.
899
900**Atomic service API**: This API can be used in atomic services since API version 11.
901
902**System capability**: SystemCapability.HiviewDFX.HiAppEvent
903
904| Name     | Value  | Description          |
905| --------- | ---- | -------------- |
906| FAULT     | 1    | Fault event.|
907| STATISTIC | 2    | Statistical event.|
908| SECURITY  | 3    | Security event.|
909| BEHAVIOR  | 4    | Behavior event.|
910
911
912## hiappevent.domain<sup>11+</sup>
913
914Defines the domain name of predefined events.
915
916**Atomic service API**: This API can be used in atomic services since API version 11.
917
918**System capability**: SystemCapability.HiviewDFX.HiAppEvent
919
920| Name| Type  | Read Only  | Description      |
921| ---  | ------ | ------ | ---------- |
922| OS   | string | Yes| System domain.|
923
924
925## hiappevent.event
926
927Defines the names of predefined events.
928
929**System capability**: SystemCapability.HiviewDFX.HiAppEvent
930
931| Name                     | Type  | Read Only  | Description                |
932| ------------------------- | ------ | ------ | -------------------- |
933| USER_LOGIN                | string | Yes| User login event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
934| USER_LOGOUT               | string | Yes| User logout event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
935| DISTRIBUTED_SERVICE_START | string | Yes| Distributed service startup event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
936| APP_CRASH<sup>11+</sup>   | string | Yes| Application crash event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
937| APP_FREEZE<sup>11+</sup>  | string | Yes| Application freeze event.<br>**Atomic service API**: This API can be used in atomic services since API version 11.      |
938| APP_LAUNCH<sup>12+</sup>  | string | Yes| Event indicating the application launch duration.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
939| SCROLL_JANK<sup>12+</sup> | string | Yes| Event indicating frame loss during swiping.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
940| CPU_USAGE_HIGH<sup>12+</sup> | string | Yes| Event indicating a high CPU usage.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
941| BATTERY_USAGE<sup>12+</sup> | string | Yes| Event indicating battery usage statistics.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
942| RESOURCE_OVERLIMIT<sup>12+</sup> | string | Yes| Event indicating an application resource leakage.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
943| ADDRESS_SANITIZER<sup>12+</sup> | string | Yes| Address sanitizer event.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
944| MAIN_THREAD_JANK<sup>12+</sup> | string | Yes| Main thread jank event.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
945
946
947## hiappevent.param
948
949Defines the names of predefined event parameters.
950
951**Atomic service API**: This API can be used in atomic services since API version 11.
952
953**System capability**: SystemCapability.HiviewDFX.HiAppEvent
954
955| Name                           | Type  | Read Only  | Description              |
956| ------------------------------- | ------ | ------ | ------------------ |
957| USER_ID                         | string | Yes| Custom user ID.    |
958| DISTRIBUTED_SERVICE_NAME        | string | Yes| Distributed service name.  |
959| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes| Distributed service instance ID.|
960