1# Development of Application Event Logging 2 3## Introduction 4 5A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage. 6 7HiAppEvent is a module that provides the event logging function for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of applications. 8 9## Basic Concepts 10 11- **Logging** 12 13 Logs changes caused by user operations to provide service data for development, product, and O&M analysis. 14 15## Event Design Specifications 16 17- Event domain: identifies the domain of an event. You are advised to set this parameter to the service module name to differentiate service modules. 18- Event name: specifies the name of an event. You are advised to set this parameter to a specific service name to differentiate services. 19- Event type: specifies the type of an event. Four event types are supported: 20 - Behavior event: used to record the daily operation behavior of a user, for example, button click and page redirection. 21 - Fault event: used to locate and analyze application faults, for example, frame freezing, network disconnection, and call drop. 22 - Statistical event: used to collect statistics on key application behaviors, for example, usage duration and number of visits. 23 - Security event: used to record events related to application security, for example, password change and user authorization. 24- Event parameter: specifies the parameters of an event. Each event can contain a group of parameters. You are advised to set this parameter to an event attribute or event context to depict the event details. 25 26## Available APIs 27 28The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiviewdfx-hiappevent.md). 29 30**Table 1** APIs for application event logging 31 32| API | Description | 33| ------------------------------------------------------------ | ---------------------------------------------------- | 34| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| 35| write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. | 36 37**Table 3** APIs for watcher management 38 39| API | Description | 40| -------------------------------------------------- | -------------------------------------------- | 41| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher to subscribe to expected application events.| 42| removeWatcher(Watcher watcher): void | Adds an event watcher to unsubscribe from expected application events.| 43 44## How to Develop 45 46The following example illustrates how to log and subscribe to button click events of users. 47 481. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **entryability** > **EntryAbility.ts**, and double-click **EntryAbility.ts**. Then, add an event watcher to subscribe to button click events. The complete sample code is as follows: 49 50 ```js 51 import hilog from '@ohos.hilog'; 52 import Ability from '@ohos.application.Ability' 53 import Window from '@ohos.window' 54 import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' 55 56 export default class EntryAbility extends Ability { 57 onCreate(want, launchParam) { 58 hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); 59 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 60 hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); 61 hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? ''); 62 63 hiAppEvent.addWatcher({ 64 // Add a watcher. You can customize the watcher name. The system identifies different watchers based on their names. 65 name: "watcher1", 66 // Subscribe to application events you are interested in, for example, button click events. 67 appEventFilters: [{ domain: "button" }], 68 // Set the subscription callback trigger condition. In this example, a callback is triggered if one event is logged. 69 triggerCondition: { row: 1 }, 70 // Implement the subscription callback function to apply custom processing to the event logging data obtained through subscription. 71 onTrigger: function (curRow, curSize, holder) { 72 // If the watcher incurs an error while it is working, return a null holder object after recording the error in the log. 73 if (holder == null) { 74 hilog.error(0x0000, 'testTag', "HiAppEvent holder is null") 75 return 76 } 77 let eventPkg = null 78 // Fetch the subscription event package based on the specified threshold (512 KB by default) until all subscription event data is fetched. 79 // If all subscription event data is fetched, return a null event package object. The subscription callback process is ended. 80 while ((eventPkg = holder.takeNext()) != null) { 81 // Apply custom processing to the event logging data in the event package, for example, print the event logging data in the log. 82 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId) 83 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row) 84 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size) 85 for (const eventInfo of eventPkg.data) { 86 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo) 87 } 88 } 89 } 90 }) 91 } 92 } 93 942. Choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add a button, and enable logging of button click events in its **onClick** function. The complete sample code is as follows: 95 96 ```js 97 import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' 98 import hilog from '@ohos.hilog' 99 100 @Entry 101 @Component 102 struct Index { 103 @State message: string = 'Hello World' 104 105 build() { 106 Row() { 107 Column() { 108 Text(this.message) 109 .fontSize(50) 110 .fontWeight(FontWeight.Bold) 111 112 Button("writeTest").onClick(()=>{ 113 // Enable event logging in the button click function to log button click events. 114 hiAppEvent.write({ 115 // Define the event domain. 116 domain: "button", 117 // Define the event name. 118 name: "click", 119 // Define the event type. 120 eventType: hiAppEvent.EventType.BEHAVIOR, 121 // Define event parameters. 122 params: { click_time: 100 } 123 }).then(() => { 124 hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) 125 }).catch((err) => { 126 hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) 127 }) 128 }) 129 } 130 .width('100%') 131 } 132 .height('100%') 133 } 134 } 135 ``` 136 1373. Touch the run button on the IDE to run the project. Then, touch the **writeTest** button on the application UI to trigger application event logging. 138 1394. View the information printed in the **Log** window. If logging of the button click event is successful, you will see a message indicating successful event logging as well as the log information specific to processing of the event logging data in the subscription callback. 140 141 ```js 142 HiAppEvent success to write event 143 144 HiAppEvent eventPkg.packageId=0 145 HiAppEvent eventPkg.row=1 146 HiAppEvent eventPkg.size=124 147 HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100} 148 ``` 149