• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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```js
13import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
14```
15
16## hiAppEvent.write
17
18write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback<void>): void
19
20Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses an asynchronous callback to return the result.
21
22**System capability**: SystemCapability.HiviewDFX.HiAppEvent
23
24**Parameters**
25
26| Name  | Type                          | Mandatory| Description          |
27| -------- | ------------------------------ | ---- | -------------- |
28| info     | [AppEventInfo](#appeventinfo) | Yes  | Application event object.|
29| callback | AsyncCallback<void>      | Yes  | Callback used to return the result.|
30
31**Error codes**
32
33For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
34
35| ID| Error Message                                     |
36| -------- | --------------------------------------------- |
37| 11100001 | Function is disabled.                         |
38| 11101001 | Invalid event domain.                         |
39| 11101002 | Invalid event name.                           |
40| 11101003 | Invalid number of event parameters.           |
41| 11101004 | Invalid string length of the event parameter. |
42| 11101005 | Invalid event parameter name.                 |
43| 11101006 | Invalid array length of the event parameter.  |
44
45**Example**
46
47```js
48hiAppEvent.write({
49    domain: "test_domain",
50    name: "test_event",
51    eventType: hiAppEvent.EventType.FAULT,
52    params: {
53        int_data: 100,
54        str_data: "strValue"
55    }
56}, (err) => {
57    if (err) {
58        console.error(`code: ${err.code}, message: ${err.message}`);
59        return;
60    }
61    console.log(`success to write event`);
62});
63```
64
65## hiAppEvent.write
66
67write(info: [AppEventInfo](#appeventinfo)): Promise<void>
68
69Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses a promise to return the result.
70
71**System capability**: SystemCapability.HiviewDFX.HiAppEvent
72
73**Parameters**
74
75| Name| Type                          | Mandatory| Description          |
76| ------ | ------------------------------ | ---- | -------------- |
77| info   | [AppEventInfo](#appeventinfo) | Yes  | Application event object.|
78
79**Return value**
80
81| Type               | Description         |
82| ------------------- | ------------- |
83| Promise<void> | Promise used to return the result.|
84
85**Error codes**
86
87For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
88
89| ID| Error Message                                     |
90| -------- | --------------------------------------------- |
91| 11100001 | Function is disabled.                         |
92| 11101001 | Invalid event domain.                         |
93| 11101002 | Invalid event name.                           |
94| 11101003 | Invalid number of event parameters.           |
95| 11101004 | Invalid string length of the event parameter. |
96| 11101005 | Invalid event parameter name.                 |
97| 11101006 | Invalid array length of the event parameter.  |
98
99**Example**
100
101```js
102hiAppEvent.write({
103    domain: "test_domain",
104    name: "test_event",
105    eventType: hiAppEvent.EventType.FAULT,
106    params: {
107        int_data: 100,
108        str_data: "strValue"
109    }
110}).then(() => {
111    console.log(`success to write event`);
112}).catch((err) => {
113    console.error(`code: ${err.code}, message: ${err.message}`);
114});
115```
116
117## AppEventInfo
118
119Defines parameters for an **AppEventInfo** object.
120
121**System capability**: SystemCapability.HiviewDFX.HiAppEvent
122
123| Name     | Type                   | Mandatory| Description                                                        |
124| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
125| domain    | string                  | Yes  | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
126| name      | string                  | Yes  | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
127| eventType | [EventType](#eventtype) | Yes  | Event type.                                                  |
128| params    | object                  | Yes  | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).<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.|
129
130## hiAppEvent.configure
131
132configure(config: [ConfigOption](configoption)): void
133
134Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files.
135
136**System capability**: SystemCapability.HiviewDFX.HiAppEvent
137
138**Parameters**
139
140| Name| Type                         | Mandatory| Description                    |
141| ------ | ----------------------------- | ---- | ------------------------ |
142| config | [ConfigOption](#configoption) | Yes  | Configuration items for application event logging.|
143
144**Error codes**
145
146For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
147
148| ID| Error Message                        |
149| -------- | -------------------------------- |
150| 11103001 | Invalid max storage quota value. |
151
152**Example**
153
154```js
155// Disable the event logging function.
156hiAppEvent.configure({
157    disable: true
158});
159
160// Set the maximum size of the file storage directory to 100 MB.
161hiAppEvent.configure({
162    maxStorage: '100M'
163});
164```
165
166## ConfigOption
167
168Configures options for application event logging.
169
170**System capability**: SystemCapability.HiviewDFX.HiAppEvent
171
172| Name      | Type   | Mandatory| Description                                                        |
173| ---------- | ------- | ---- | ------------------------------------------------------------ |
174| 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.|
175| maxStorage | string  | No  | Maximum size of 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.|
176
177## hiAppEvent.addWatcher
178
179addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpackageholder)
180
181Adds a watcher to subscribe to application events.
182
183**System capability**: SystemCapability.HiviewDFX.HiAppEvent
184
185**Parameters**
186
187| Name | Type                | Mandatory| Description            |
188| ------- | -------------------- | ---- | ---------------- |
189| watcher | [Watcher](#watcher) | Yes  | Watcher for application events.|
190
191**Return value**
192
193| Type                                            | Description                                |
194| ------------------------------------------------ | ------------------------------------ |
195| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** will be returned.|
196
197**Error codes**
198
199For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
200
201| ID| Error Message                       |
202| -------- | ------------------------------- |
203| 11102001 | Invalid watcher name.           |
204| 11102002 | Invalid filtering event domain. |
205| 11102003 | Invalid row value.              |
206| 11102004 | Invalid size value.             |
207| 11102005 | Invalid timeout value.          |
208
209**Example**
210
211```js
212// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
213hiAppEvent.addWatcher({
214    name: "watcher1",
215    appEventFilters: [
216        {
217            domain: "test_domain",
218            eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
219        }
220    ],
221    triggerCondition: {
222        row: 10,
223        size: 1000,
224        timeOut: 1
225    },
226    onTrigger: function (curRow, curSize, holder) {
227        if (holder == null) {
228            console.error("holder is null");
229            return;
230        }
231        let eventPkg = null;
232        while ((eventPkg = holder.takeNext()) != null) {
233            console.info(`eventPkg.packageId=${eventPkg.packageId}`);
234            console.info(`eventPkg.row=${eventPkg.row}`);
235            console.info(`eventPkg.size=${eventPkg.size}`);
236            for (const eventInfo of eventPkg.data) {
237                console.info(`eventPkg.data=${eventInfo}`);
238            }
239        }
240    }
241});
242
243// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
244let holder = hiAppEvent.addWatcher({
245    name: "watcher2",
246});
247if (holder != null) {
248    let eventPkg = null;
249    while ((eventPkg = holder.takeNext()) != null) {
250        console.info(`eventPkg.packageId=${eventPkg.packageId}`);
251        console.info(`eventPkg.row=${eventPkg.row}`);
252        console.info(`eventPkg.size=${eventPkg.size}`);
253        for (const eventInfo of eventPkg.data) {
254            console.info(`eventPkg.data=${eventInfo}`);
255        }
256    }
257}
258```
259
260## hiAppEvent.removeWatcher
261
262removeWatcher(watcher: [Watcher](#watcher)): void
263
264Removes a watcher to unsubscribe from application events.
265
266**System capability**: SystemCapability.HiviewDFX.HiAppEvent
267
268**Parameters**
269
270| Name | Type                | Mandatory| Description            |
271| ------- | -------------------- | ---- | ---------------- |
272| watcher | [Watcher](#watcher) | Yes  | Watcher for application events.|
273
274**Error codes**
275
276For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
277
278| ID| Error Message             |
279| -------- | --------------------- |
280| 11102001 | Invalid watcher name. |
281
282**Example**
283
284```js
285// 1. Define a watcher for application events.
286let watcher = {
287    name: "watcher1",
288}
289
290// 2. Add the watcher to subscribe to application events.
291hiAppEvent.addWatcher(watcher);
292
293// 3. Remove the watcher to unsubscribe from application events.
294hiAppEvent.removeWatcher(watcher);
295```
296
297## Watcher
298
299Defines parameters for a **Watcher** object.
300
301**System capability**: SystemCapability.HiviewDFX.HiAppEvent
302
303| Name            | Type                                                        | Mandatory| Description                                                        |
304| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
305| name             | string                                                       | Yes  | Unique name of the watcher.                            |
306| triggerCondition | [TriggerCondition](#triggercondition)                        | No  | Subscription callback triggering condition. This parameter takes effect only when it is passed together with the callback.          |
307| appEventFilters  | [AppEventFilter](#appeventfilter)[]                          | No  | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered.              |
308| onTrigger        | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void | No  | Subscription callback, which takes effect only when it is passed together with the callback triggering condition. 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.|
309
310## TriggerCondition
311
312Defines callback triggering conditions. Subscription callback is triggered when any condition is met.
313
314**System capability**: SystemCapability.HiviewDFX.HiAppEvent
315
316| Name   | Type  | Mandatory| Description                                  |
317| ------- | ------ | ---- | -------------------------------------- |
318| row     | number | No  | Number of events.            |
319| size    | number | No  | Event data size, in bytes.|
320| timeOut | number | No  | Timeout interval, in unit of 30s.   |
321
322## AppEventFilter
323
324Defines parameters for an **AppEventFilter** object.
325
326**System capability**: SystemCapability.HiviewDFX.HiAppEvent
327
328| Name      | Type                     | Mandatory| Description                    |
329| ---------- | ------------------------- | ---- | ------------------------ |
330| domain     | string                    | Yes  | Event domain.    |
331| eventTypes | [EventType](#eventtype)[] | No  | Event types.|
332
333## AppEventPackageHolder
334
335Defines a subscription data holder for processing subscription events.
336
337**System capability**: SystemCapability.HiviewDFX.HiAppEvent
338
339### constructor
340
341constructor(watcherName: string)
342
343Constructor of the **Watcher** class. When a watcher is added, the system automatically calls this API to create a subscription data holder object for the watcher and returns the holder object to the application.
344
345**System capability**: SystemCapability.HiviewDFX.HiAppEvent
346
347**Parameters**
348
349| Name| Type             | Mandatory| Description                    |
350| ------ | ----------------- | ---- | ------------------------ |
351| watcherName | string | Yes  | Watcher name.|
352
353**Example**
354
355```js
356let holder = hiAppEvent.addWatcher({
357    name: "watcher",
358});
359```
360
361### setSize
362
363setSize(size: number): void
364
365Sets the threshold for the data size of the application event package obtained each time.
366
367**System capability**: SystemCapability.HiviewDFX.HiAppEvent
368
369**Parameters**
370
371| Name| Type  | Mandatory| Description                                        |
372| ------ | ------ | ---- | -------------------------------------------- |
373| size   | number | Yes  | Data size threshold, in bytes. The default value is **512*1024**.|
374
375**Error codes**
376
377For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
378
379| ID| Error Message           |
380| -------- | ------------------- |
381| 11104001 | Invalid size value. |
382
383**Example**
384
385```js
386let holder = hiAppEvent.addWatcher({
387    name: "watcher",
388});
389holder.setSize(1000);
390```
391
392### takeNext
393
394takeNext(): [AppEventPackage](#appeventpackage)
395
396Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.
397
398**System capability**: SystemCapability.HiviewDFX.HiAppEvent
399
400**Example**
401
402```js
403let holder = hiAppEvent.addWatcher({
404    name: "watcher",
405});
406let eventPkg = holder.takeNext();
407```
408
409## AppEventPackage
410
411Defines parameters for an **AppEventPackage** object.
412
413**System capability**: SystemCapability.HiviewDFX.HiAppEvent
414
415| Name     | Type    | Mandatory| Description                          |
416| --------- | -------- | ---- | ------------------------------ |
417| packageId | number   | Yes  | Event package ID, which is named from **0** in ascending order.   |
418| row       | number   | Yes  | Number of events in the event package.            |
419| size      | number   | Yes  | Event size of the event package, in bytes.|
420| data      | string[] | Yes  | Event data in the event package.            |
421
422## hiAppEvent.clearData
423
424clearData(): void
425
426Clears local application event logging data.
427
428**System capability**: SystemCapability.HiviewDFX.HiAppEvent
429
430**Example**
431
432```js
433hiAppEvent.clearData();
434```
435
436
437## EventType
438
439Enumerates event types.
440
441**System capability**: SystemCapability.HiviewDFX.HiAppEvent
442
443| Name     | Value  | Description          |
444| --------- | ---- | -------------- |
445| FAULT     | 1    | Fault event.|
446| STATISTIC | 2    | Statistical event.|
447| SECURITY  | 3    | Security event.|
448| BEHAVIOR  | 4    | Behavior event.|
449
450
451## event
452
453Provides constants that define the names of all predefined events.
454
455**System capability**: SystemCapability.HiviewDFX.HiAppEvent
456
457| Name                     | Type  | Description                |
458| ------------------------- | ------ | -------------------- |
459| USER_LOGIN                | string | User login event.      |
460| USER_LOGOUT               | string | User logout event.      |
461| DISTRIBUTED_SERVICE_START | string | Distributed service startup event.|
462
463
464## param
465
466Provides constants that define the names of all predefined event parameters.
467
468**System capability**: SystemCapability.HiviewDFX.HiAppEvent
469
470| Name                           | Type  | Description              |
471| ------------------------------- | ------ | ------------------ |
472| USER_ID                         | string | Custom user ID.    |
473| DISTRIBUTED_SERVICE_NAME        | string | Distributed service name.  |
474| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID.|
475