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