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<void>): 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<void> | 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<void> 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<void> | 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. An event parameter has 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<string, ParamType>, domain: string, name?: string): Promise<void> 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<string, [ParamType](#paramtype12)> | 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<void> | 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 event param`); 312}).catch((err: BusinessError) => { 313 hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`); 314}); 315``` 316 317## hiAppEvent.setEventConfig<sup>15+</sup> 318 319setEventConfig(name: string, config: Record<string, ParamType>): Promise<void> 320 321Sets the custom threshold triggering condition for an event. This API uses a promise to return the result. In the same lifecycle, you can customize the parameters related to the event threshold triggering condition based on the event name. Currently, only the **MAIN_THREAD_JANK** event is supported. For details about the parameter configuration, see [Main Thread Jank Event Overview](../../dfx/hiappevent-watcher-mainthreadjank-events.md). 322 323**Atomic service API**: This API can be used in atomic services since API version 15. 324 325**System capability**: SystemCapability.HiviewDFX.HiAppEvent 326 327**Parameters** 328 329| Name| Type | Mandatory| Description | 330| ------ | ------------------------------ | ---- | -------------- | 331| name | string | Yes| Event name.| 332| config | Record<string, ParamType> | Yes| Custom parameter object. The parameter name and value are defined as follows:<br>- The parameter name contains a maximum of 1024 characters, which is of the string type and cannot be empty.<br>- The parameter value is of the ParamType and contains a maximum of 1024 characters.| 333 334**Return value** 335 336| Type | Description | 337| ------------------- | ------------- | 338| Promise<void> | Promise used to return the result.| 339 340**Error codes** 341 342For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 343 344| ID| Error Message | 345| -------- | --------------------------------------------- | 346| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed. | 347 348**Example** 349 350The following describes how to customize the **log_type** parameter for the **MAIN_THREAD_JANK** event. 351 352Set **log_type** to **0** to collect the stack or trace: 353```ts 354import { BusinessError } from '@kit.BasicServicesKit'; 355import { hilog } from '@kit.PerformanceAnalysisKit'; 356 357let params: Record<string, hiAppEvent.ParamType> = { 358 "log_type": "0" 359}; 360 361hiAppEvent.setEventConfig(hiAppEvent.event.MAIN_THREAD_JANK, params).then(() => { 362 hilog.info(0x0000, 'hiAppEvent', `success to set event config`); 363}).catch((err: BusinessError) => { 364 hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`); 365}); 366``` 367 368Set **log_type** to **1** to collect only the call stack: 369```ts 370import { BusinessError } from '@kit.BasicServicesKit'; 371import { hilog } from '@kit.PerformanceAnalysisKit'; 372 373let params: Record<string, hiAppEvent.ParamType> = { 374 "log_type": "1", 375 "sample_interval": "100", 376 "ignore_startup_time": "11", 377 "sample_count": "21", 378 "report_times_per_app": "3", 379}; 380hiAppEvent.setEventConfig(hiAppEvent.event.MAIN_THREAD_JANK, params).then(() => { 381 hilog.info(0x0000, 'hiAppEvent', `success to set event config`); 382}).catch((err: BusinessError) => { 383 hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`); 384}); 385``` 386 387Set **log_type** to **2** to collect only the trace: 388```ts 389import { BusinessError } from '@kit.BasicServicesKit'; 390import { hilog } from '@kit.PerformanceAnalysisKit'; 391 392let params: Record<string, hiAppEvent.ParamType> = { 393 "log_type": "2" 394}; 395hiAppEvent.setEventConfig(hiAppEvent.event.MAIN_THREAD_JANK, params).then(() => { 396 hilog.info(0x0000, 'hiAppEvent', `success to set event config`); 397}).catch((err: BusinessError) => { 398 hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`); 399}); 400``` 401 402## ParamType<sup>12+</sup> 403 404type ParamType = number | string | boolean | Array<string> 405 406Type of a custom event parameter value. 407 408**Atomic service API**: This API can be used in atomic services since API version 12. 409 410**System capability**: SystemCapability.HiviewDFX.HiAppEvent 411 412| Type | Description | 413|--------------------------|-------------------| 414| number | Number. | 415| string | String. | 416| boolean | The value is true or false. | 417| Array<string> | The value is an array of strings. | 418 419## hiAppEvent.configure 420 421configure(config: ConfigOption): void 422 423Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. 424 425**Atomic service API**: This API can be used in atomic services since API version 11. 426 427**System capability**: SystemCapability.HiviewDFX.HiAppEvent 428 429**Parameters** 430 431| Name| Type | Mandatory| Description | 432| ------ | ----------------------------- | ---- | ------------------------ | 433| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| 434 435**Error codes** 436 437For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 438 439| ID| Error Message | 440| -------- | -------------------------------- | 441| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 442| 11103001 | Invalid max storage quota value. | 443 444**Example** 445 446```ts 447// Disable the event logging function. 448let config1: hiAppEvent.ConfigOption = { 449 disable: true, 450}; 451hiAppEvent.configure(config1); 452 453// Set the maximum size of the file storage directory to 100 MB. 454let config2: hiAppEvent.ConfigOption = { 455 maxStorage: '100M', 456}; 457hiAppEvent.configure(config2); 458``` 459 460## ConfigOption 461 462Provides configuration options for application event logging. 463 464**Atomic service API**: This API can be used in atomic services since API version 11. 465 466**System capability**: SystemCapability.HiviewDFX.HiAppEvent 467 468| Name | Type | Mandatory| Description | 469| ---------- | ------- | ---- | ------------------------------------------------------------ | 470| 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.| 471| 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.| 472 473## hiAppEvent.setUserId<sup>11+</sup> 474 475setUserId(name: string, value: string): void 476 477Sets a user ID. 478 479**Atomic service API**: This API can be used in atomic services since API version 11. 480 481**System capability**: SystemCapability.HiviewDFX.HiAppEvent 482 483**Parameters** 484 485| Name | Type | Mandatory| Description | 486| --------- | ------------------------- | ---- | ------------- | 487| 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. | 488| 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.| 489 490**Error codes** 491 492| ID| Error Message | 493| ------- | ----------------- | 494| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 495 496**Example** 497 498```ts 499import { hilog } from '@kit.PerformanceAnalysisKit'; 500 501try { 502 hiAppEvent.setUserId('key', 'value'); 503} catch (error) { 504 hilog.error(0x0000, 'hiAppEvent', `failed to setUserId event, code=${error.code}`); 505} 506``` 507 508## hiAppEvent.getUserId<sup>11+</sup> 509 510getUserId(name: string): string 511 512Obtains the value set by **setUserId**. 513 514**Atomic service API**: This API can be used in atomic services since API version 11. 515 516**System capability**: SystemCapability.HiviewDFX.HiAppEvent 517 518**Parameters** 519 520| Name | Type | Mandatory| Description | 521| --------- | ----------------------- | ---- | ---------- | 522| 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.| 523 524**Return value** 525 526| Type | Description | 527| ------ | ------------------------------- | 528| string | Value of a user ID. If no user ID is found, an empty string is returned.| 529 530**Error codes** 531 532| ID| Error Message | 533| ------- | ----------------- | 534| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 535 536**Example** 537 538```ts 539import { hilog } from '@kit.PerformanceAnalysisKit'; 540 541hiAppEvent.setUserId('key', 'value'); 542try { 543 let value: string = hiAppEvent.getUserId('key'); 544 hilog.info(0x0000, 'hiAppEvent', `getUserId event was successful, userId=${value}`); 545} catch (error) { 546 hilog.error(0x0000, 'hiAppEvent', `failed to getUserId event, code=${error.code}`); 547} 548``` 549 550## hiAppEvent.setUserProperty<sup>11+</sup> 551 552setUserProperty(name: string, value: string): void 553 554Sets user properties. 555 556**Atomic service API**: This API can be used in atomic services since API version 11. 557 558**System capability**: SystemCapability.HiviewDFX.HiAppEvent 559 560**Parameters** 561 562| Name | Type | Mandatory| Description | 563| --------- | ------------------------- | ---- | -------------- | 564| 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. | 565| value | string | Yes | Value of a user property. It can contain a maximum of 1024 characters. If the value is **null** or left empty, the user property is cleared. | 566 567**Error codes** 568 569| ID| Error Message | 570| ------- | ----------------- | 571| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 572 573**Example** 574 575```ts 576import { hilog } from '@kit.PerformanceAnalysisKit'; 577 578try { 579 hiAppEvent.setUserProperty('key', 'value'); 580} catch (error) { 581 hilog.error(0x0000, 'hiAppEvent', `failed to setUserProperty event, code=${error.code}`); 582} 583``` 584 585## hiAppEvent.getUserProperty<sup>11+</sup> 586 587getUserProperty(name: string): string 588 589Obtains the value set by **setUserProperty**. 590 591**Atomic service API**: This API can be used in atomic services since API version 11. 592 593**System capability**: SystemCapability.HiviewDFX.HiAppEvent 594 595**Parameters** 596 597| Name | Type | Mandatory| Description | 598| --------- | ----------------------- | ---- | ---------- | 599| 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.| 600 601**Return value** 602 603| Type | Description | 604| ------ | -------------------------------- | 605| string | Value of a user property. If no user ID is found, an empty string is returned.| 606 607**Error codes** 608 609| ID| Error Message | 610| ------- | ----------------- | 611| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 612 613**Example** 614 615```ts 616import { hilog } from '@kit.PerformanceAnalysisKit'; 617 618hiAppEvent.setUserProperty('key', 'value'); 619try { 620 let value: string = hiAppEvent.getUserProperty('key'); 621 hilog.info(0x0000, 'hiAppEvent', `getUserProperty event was successful, userProperty=${value}`); 622} catch (error) { 623 hilog.error(0x0000, 'hiAppEvent', `failed to getUserProperty event, code=${error.code}`); 624} 625``` 626 627## hiAppEvent.addWatcher 628 629addWatcher(watcher: Watcher): AppEventPackageHolder 630 631Adds a watcher to subscribe to application events. 632 633**Atomic service API**: This API can be used in atomic services since API version 11. 634 635**System capability**: SystemCapability.HiviewDFX.HiAppEvent 636 637**Parameters** 638 639| Name | Type | Mandatory| Description | 640| ------- | -------------------- | ---- | ---------------- | 641| watcher | [Watcher](#watcher) | Yes | Watcher for application events.| 642 643**Return value** 644 645| Type | Description | 646| ------------------------------------------------ | ------------------------------------ | 647| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** will be returned.| 648 649**Error codes** 650 651For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 652 653| ID| Error Message | 654| -------- | ------------------------------- | 655| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 656| 11102001 | Invalid watcher name. | 657| 11102002 | Invalid filtering event domain. | 658| 11102003 | Invalid row value. | 659| 11102004 | Invalid size value. | 660| 11102005 | Invalid timeout value. | 661 662**Example** 663 664```ts 665import { hilog } from '@kit.PerformanceAnalysisKit'; 666 667// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered. 668hiAppEvent.addWatcher({ 669 name: "watcher1", 670 appEventFilters: [ 671 { 672 domain: "test_domain", 673 eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] 674 } 675 ], 676 triggerCondition: { 677 row: 10, 678 size: 1000, 679 timeOut: 1 680 }, 681 onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => { 682 if (holder == null) { 683 hilog.error(0x0000, 'hiAppEvent', "holder is null"); 684 return; 685 } 686 hilog.info(0x0000, 'hiAppEvent', `curRow=${curRow}, curSize=${curSize}`); 687 let eventPkg: hiAppEvent.AppEventPackage | null = null; 688 while ((eventPkg = holder.takeNext()) != null) { 689 hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`); 690 hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`); 691 hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`); 692 for (const eventInfo of eventPkg.data) { 693 hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`); 694 } 695 } 696 } 697}); 698 699// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder. 700// 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. 701let holder = hiAppEvent.addWatcher({ 702 name: "watcher2", 703}); 704if (holder != null) { 705 let eventPkg: hiAppEvent.AppEventPackage | null = null; 706 while ((eventPkg = holder.takeNext()) != null) { 707 hilog.info(0x0000, 'hiAppEvent', `eventPkg.packageId=${eventPkg.packageId}`); 708 hilog.info(0x0000, 'hiAppEvent', `eventPkg.row=${eventPkg.row}`); 709 hilog.info(0x0000, 'hiAppEvent', `eventPkg.size=${eventPkg.size}`); 710 for (const eventInfo of eventPkg.data) { 711 hilog.info(0x0000, 'hiAppEvent', `eventPkg.data=${eventInfo}`); 712 } 713 } 714} 715 716// 3. You can have the watcher processed the subscription event in the onReceive function. 717hiAppEvent.addWatcher({ 718 name: "watcher3", 719 appEventFilters: [ 720 { 721 domain: "test_domain", 722 eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] 723 } 724 ], 725 onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => { 726 hilog.info(0x0000, 'hiAppEvent', `domain=${domain}`); 727 for (const eventGroup of appEventGroups) { 728 hilog.info(0x0000, 'hiAppEvent', `eventName=${eventGroup.name}`); 729 for (const eventInfo of eventGroup.appEventInfos) { 730 hilog.info(0x0000, 'hiAppEvent', `event=${JSON.stringify(eventInfo)}`, ); 731 } 732 } 733 } 734}); 735``` 736 737## hiAppEvent.removeWatcher 738 739removeWatcher(watcher: Watcher): void 740 741Removes a watcher to unsubscribe from application events. 742 743**Atomic service API**: This API can be used in atomic services since API version 11. 744 745**System capability**: SystemCapability.HiviewDFX.HiAppEvent 746 747**Parameters** 748 749| Name | Type | Mandatory| Description | 750| ------- | -------------------- | ---- | ---------------- | 751| watcher | [Watcher](#watcher) | Yes | Watcher for application events.| 752 753**Error codes** 754 755For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 756 757| ID| Error Message | 758| -------- | --------------------- | 759| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 760| 11102001 | Invalid watcher name. | 761 762**Example** 763 764```ts 765// 1. Define a watcher for application events. 766let watcher: hiAppEvent.Watcher = { 767 name: "watcher1", 768} 769 770// 2. Add the watcher to subscribe to application events. 771hiAppEvent.addWatcher(watcher); 772 773// 3. Remove the watcher to unsubscribe from application events. 774hiAppEvent.removeWatcher(watcher); 775``` 776 777## Watcher 778 779Defines parameters for a **Watcher** object. 780 781**Atomic service API**: This API can be used in atomic services since API version 11. 782 783**System capability**: SystemCapability.HiviewDFX.HiAppEvent 784 785| Name | Type | Mandatory| Description | 786| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 787| name | string | Yes | Unique name of a watcher. | 788| triggerCondition | [TriggerCondition](#triggercondition) | No | Subscription callback triggering condition. This parameter takes effect only when it is passed together with **onTrigger**. | 789| appEventFilters | [AppEventFilter](#appeventfilter)[] | No | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered. | 790| 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.| 791| 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.| 792 793## TriggerCondition 794 795Defines callback triggering conditions. A callback is triggered when any specified condition is met. 796 797**Atomic service API**: This API can be used in atomic services since API version 11. 798 799**System capability**: SystemCapability.HiviewDFX.HiAppEvent 800 801| Name | Type | Mandatory| Description | 802| ------- | ------ | ---- | -------------------------------------- | 803| 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. | 804| 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.| 805| 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. | 806 807## AppEventFilter 808 809Defines parameters for an **AppEventFilter** object. 810 811**Atomic service API**: This API can be used in atomic services since API version 11. 812 813**System capability**: SystemCapability.HiviewDFX.HiAppEvent 814 815| Name | Type | Mandatory| Description | 816| ---------- | ------------------------- | ---- | ------------------------ | 817| domain | string | Yes | Event domain. | 818| eventTypes | [EventType](#eventtype)[] | No | Event types.| 819| names<sup>11+</sup> | string[] | No | Names of the events to be subscribed.| 820 821## AppEventPackageHolder 822 823Defines a subscription data holder for processing subscription events. 824 825### constructor 826 827constructor(watcherName: string) 828 829A constructor used to create a holder object for subscription data. It is associated with a **Watcher** object based on its name. 830 831**Atomic service API**: This API can be used in atomic services since API version 11. 832 833**System capability**: SystemCapability.HiviewDFX.HiAppEvent 834 835**Parameters** 836 837| Name| Type | Mandatory| Description | 838| ------ | ----------------- | ---- | ------------------------ | 839| watcherName | string | Yes | Watcher name.| 840 841**Example** 842 843```ts 844let holder1: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher1"); 845``` 846 847### setSize 848 849setSize(size: number): void 850 851Sets the threshold for the data size of the application event package obtained each time. 852 853**Atomic service API**: This API can be used in atomic services since API version 11. 854 855**System capability**: SystemCapability.HiviewDFX.HiAppEvent 856 857**Parameters** 858 859| Name| Type | Mandatory| Description | 860| ------ | ------ | ---- | -------------------------------------------- | 861| size | number | Yes | Data size, in bytes. The value is greater than or equal to 0, otherwise, an exception is thrown.| 862 863**Error codes** 864 865For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 866 867| ID| Error Message | 868| -------- | ------------------- | 869| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 870| 11104001 | Invalid size value. | 871 872**Example** 873 874```ts 875let holder2: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher2"); 876holder2.setSize(1000); 877``` 878 879### setRow<sup>12+</sup> 880 881setRow(size: number): void 882 883Sets 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. 884 885**Atomic service API**: This API can be used in atomic services since API version 12. 886 887**System capability**: SystemCapability.HiviewDFX.HiAppEvent 888 889**Parameters** 890 891| Name| Type | Mandatory| Description | 892| ------ | ------ | ---- | -------------------------------------------- | 893| size | number | Yes | Number of application events. The value must be greater than 0, otherwise, an exception is thrown.| 894 895**Error codes** 896 897For details about the error codes, see [Application Event Logging Error Codes](errorcode-hiappevent.md). 898 899| ID| Error Message | 900| -------- | ------------------- | 901| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 902| 11104001 | Invalid size value. | 903 904**Example** 905 906```ts 907let holder3: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher3"); 908holder3.setRow(1000); 909``` 910 911### takeNext 912 913takeNext(): AppEventPackage 914 915Extracts 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. 9161. When an application only calls **setSize()** , the subscription events are obtained based on the data size. 9172. When an application calls **setRow()**, the subscription events are obtained based on the **number** of **setRow()** regardless of whether **setSize()** is called. 9183. If neither **setSize()** nor **setRow()** is called, one subscription event is obtained by default. 919 920**Atomic service API**: This API can be used in atomic services since API version 11. 921 922**System capability**: SystemCapability.HiviewDFX.HiAppEvent 923 924**Return value** 925 926| Type | Description | 927| ----------------------------------- | ------------------------------------------------------ | 928| [AppEventPackage](#appeventpackage) | Event package object. If all subscription event data has been retrieved, **null** is returned.| 929 930**Example** 931 932```ts 933let holder4: hiAppEvent.AppEventPackageHolder = new hiAppEvent.AppEventPackageHolder("watcher4"); 934let eventPkg = holder4.takeNext(); 935``` 936 937## AppEventPackage 938 939Defines parameters for an **AppEventPackage** object. 940 941**System capability**: SystemCapability.HiviewDFX.HiAppEvent 942 943| Name | Type | Mandatory| Description | 944| --------- | -------- | ---- | ------------------------------ | 945| 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. | 946| 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. | 947| 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.| 948| 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. | 949| 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.| 950 951## AppEventGroup<sup>11+</sup> 952 953Defines the event group returned by a subscription. 954 955**Atomic service API**: This API can be used in atomic services since API version 11. 956 957**System capability**: SystemCapability.HiviewDFX.HiAppEvent 958 959| Name | Type | Mandatory | Description | 960| ------------- | ------------------------------- | ---- | ------------- | 961| name | string | Yes | Event name. | 962| appEventInfos | Array<[AppEventInfo](#appeventinfo)> | Yes | Event object group.| 963 964## hiAppEvent.clearData 965 966clearData(): void 967 968Clears local application event logging data. 969 970**Atomic service API**: This API can be used in atomic services since API version 11. 971 972**System capability**: SystemCapability.HiviewDFX.HiAppEvent 973 974**Example** 975 976```ts 977hiAppEvent.clearData(); 978``` 979 980 981## EventType 982 983Enumerates event types. 984 985**Atomic service API**: This API can be used in atomic services since API version 11. 986 987**System capability**: SystemCapability.HiviewDFX.HiAppEvent 988 989| Name | Value | Description | 990| --------- | ---- | -------------- | 991| FAULT | 1 | Fault event.| 992| STATISTIC | 2 | Statistical event.| 993| SECURITY | 3 | Security event.| 994| BEHAVIOR | 4 | Behavior event.| 995 996 997## hiappevent.domain<sup>11+</sup> 998 999Defines the domain name of predefined events. 1000 1001**Atomic service API**: This API can be used in atomic services since API version 11. 1002 1003**System capability**: SystemCapability.HiviewDFX.HiAppEvent 1004 1005| Name| Type | Read Only | Description | 1006| --- | ------ | ------ | ---------- | 1007| OS | string | Yes| System domain.| 1008 1009 1010## hiappevent.event 1011 1012Defines the names of predefined events. 1013 1014**System capability**: SystemCapability.HiviewDFX.HiAppEvent 1015 1016| Name | Type | Read Only | Description | 1017| ------------------------- | ------ | ------ | -------------------- | 1018| USER_LOGIN | string | Yes| User login event.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1019| USER_LOGOUT | string | Yes| User logout event.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 1020| 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.| 1021| 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. | 1022| 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. | 1023| 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. | 1024| 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. | 1025| 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.| 1026| 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.| 1027| 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.| 1028| 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.| 1029| 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.| 1030 1031 1032## hiappevent.param 1033 1034Defines the names of predefined event parameters. 1035 1036**Atomic service API**: This API can be used in atomic services since API version 11. 1037 1038**System capability**: SystemCapability.HiviewDFX.HiAppEvent 1039 1040| Name | Type | Read Only | Description | 1041| ------------------------------- | ------ | ------ | ------------------ | 1042| USER_ID | string | Yes| Custom user ID. | 1043| DISTRIBUTED_SERVICE_NAME | string | Yes| Distributed service name. | 1044| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes| Distributed service instance ID.| 1045