js-apis-hiappevent.md 18.7 KB
Newer Older
S
shawn_he 已提交
1
# HiAppEvent
Z
zengyawen 已提交
2

S
shawn_he 已提交
3 4
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.

S
shawn_he 已提交
5
> **NOTE**
S
shawn_he 已提交
6
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
7

S
shawn_he 已提交
8 9

## Modules to Import
Z
zengyawen 已提交
10

L
lyj_love_code 已提交
11
```js
Z
zengyawen 已提交
12 13 14
import hiAppEvent from '@ohos.hiAppEvent';
```

S
shawn_he 已提交
15
## How to Use
S
shawn_he 已提交
16

S
shawn_he 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
Before using application event logging, you need to understand the requirements for related parameters.

**Event Domain**

An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_).

**Event Name**

An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_).

**Event Type**

An event type is an enumerated value of [EventType](#eventtype).

**Event Parameter**

An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:

- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_).
- The parameter value is a string, number, boolean, or array.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- When 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.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.

**Event Callback**

Event callback can be a callback or promise that carries the return value obtained by invoking the event logging API. You can add the processing of the return value in the event callback as follows:

- If the return value is **0**, the event verification is successful, and the event will be directly written to the event file. 
- If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored.
- If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file.

**Subscription Callback**

A subscription callback carries the subscription data obtained by invoking the watcher API. The input parameters are defined as follows:

- **curRow**: number of events.
- **curSize**: event data size, in bytes.
- **holder**: event data holder, which can be used for processing subscription events.

## hiAppEvent.write<sup>(deprecated)</sup>
S
shawn_he 已提交
58 59

write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback&lt;void&gt;): void
Z
zengyawen 已提交
60

S
shawn_he 已提交
61 62 63
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9) instead.

Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
64 65

**System capability**: SystemCapability.HiviewDFX.HiAppEvent
Z
zengyawen 已提交
66

S
shawn_he 已提交
67 68
**Parameters**

S
shawn_he 已提交
69 70 71 72 73 74
| Name   | Type                     | Mandatory| Description          |
| --------- | ------------------------- | ---- | -------------- |
| eventName | string                    | Yes  | Event name.    |
| eventType | [EventType](#eventtype)   | Yes  | Event type.    |
| keyValues | object                    | Yes  | Event parameters.    |
| callback  | AsyncCallback&lt;void&gt; | No  | Event callback.|
S
shawn_he 已提交
75 76 77

**Example**

L
lyj_love_code 已提交
78
```js
S
shawn_he 已提交
79 80
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => {
    if (err) {
S
shawn_he 已提交
81
        // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
S
shawn_he 已提交
82 83 84 85
        console.error(`failed to write event because ${err.code}`);
        return;
    }

S
shawn_he 已提交
86
    // Event writing success
S
shawn_he 已提交
87 88 89 90 91
    console.log(`success to write event: ${value}`);
});
```


S
shawn_he 已提交
92
## hiAppEvent.write<sup>(deprecated)</sup>
S
shawn_he 已提交
93 94 95

write(eventName: string, eventType: EventType, keyValues: object): Promise&lt;void&gt;

S
shawn_he 已提交
96 97 98
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9-1) instead.

Writes event information to the event file of the current day. This API uses a promise to return the result.
S
shawn_he 已提交
99 100

**System capability**: SystemCapability.HiviewDFX.HiAppEvent
S
shawn_he 已提交
101 102 103

**Parameters**

S
shawn_he 已提交
104 105 106 107 108
| Name   | Type                   | Mandatory| Description      |
| --------- | ----------------------- | ---- | ---------- |
| eventName | string                  | Yes  | Event name.|
| eventType | [EventType](#eventtype) | Yes  | Event type.|
| keyValues | object                  | Yes  | Event parameters.|
S
shawn_he 已提交
109 110 111

**Return value**

S
shawn_he 已提交
112 113
| Type               | Description                                                        |
| ------------------- | ------------------------------------------------------------ |
S
shawn_he 已提交
114
| Promise&lt;void&gt; | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.|
S
shawn_he 已提交
115 116 117

**Example**

L
lyj_love_code 已提交
118
```js
S
shawn_he 已提交
119 120
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"})
    .then((value) => {
S
shawn_he 已提交
121
        // Event writing success
Z
zengyawen 已提交
122
        console.log(`success to write event: ${value}`);
S
shawn_he 已提交
123
    }).catch((err) => {
S
shawn_he 已提交
124
        // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
S
shawn_he 已提交
125
        console.error(`failed to write event because ${err.code}`);
Z
zengyawen 已提交
126
    });
S
shawn_he 已提交
127
```
Z
zengyawen 已提交
128

S
shawn_he 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
## hiAppEvent.write<sup>9+</sup>

write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback&lt;void&gt;): void

Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

**Parameters**

| Name  | Type                          | Mandatory| Description          |
| -------- | ------------------------------ | ---- | -------------- |
| info     | [AppEventInfo](#appeventinfo9) | Yes  | Application event object.|
| callback | AsyncCallback&lt;void&gt;      | No  | Event callback.|

**Example**

```js
hiAppEvent.write({
    domain: "test_domain",
    name: "test_event",
    eventType: hiAppEvent.EventType.FAULT,
    params: {
        int_data: 100,
        str_data: "strValue"
    }
}, (err, value) => {
    if (err) {
        // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
        console.error(`failed to write event because ${err.code}`);
        return;
    }

    // Event writing success
    console.log(`success to write event: ${value}`);
});
```

## hiAppEvent.write<sup>9+</sup>

write(info: [AppEventInfo](#appeventinfo9)): Promise&lt;void&gt;

Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses a promise to return the result.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

**Parameters**

| Name| Type                          | Mandatory| Description          |
| ------ | ------------------------------ | ---- | -------------- |
| info   | [AppEventInfo](#appeventinfo9) | Yes  | Application event object.|

**Return value**

| Type               | Description                                                        |
| ------------------- | ------------------------------------------------------------ |
| Promise&lt;void&gt; | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.|

**Example**

```js
hiAppEvent.write({
    domain: "test_domain",
    name: "test_event",
    eventType: hiAppEvent.EventType.FAULT,
    params: {
        int_data: 100,
        str_data: "strValue"
    }
}).then((value) => {
    // Event writing success
    console.log(`success to write event: ${value}`);
}).catch((err) => {
    // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
    console.error(`failed to write event because ${err.code}`);
});
```

## AppEventInfo<sup>9+</sup>

Defines parameters for an **AppEventInfo** object.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name     | Type               | Mandatory| Description      |
| --------- | ----------------------- | ---- | ---------- |
| domain    | string                  | Yes  | Event domain.|
| name      | string                  | Yes  | Event name.|
| eventType | [EventType](#eventtype) | Yes  | Event type.|
| params    | object                  | Yes  | Event parameters.|
Z
zengyawen 已提交
219

S
shawn_he 已提交
220
## hiAppEvent.configure
Z
zengyawen 已提交
221

S
shawn_he 已提交
222
configure(config: ConfigOption): boolean
Z
zengyawen 已提交
223

S
shawn_he 已提交
224
Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files.
Z
zengyawen 已提交
225

S
shawn_he 已提交
226 227
**System capability**: SystemCapability.HiviewDFX.HiAppEvent

S
shawn_he 已提交
228
**Parameters**
Z
zengyawen 已提交
229

S
shawn_he 已提交
230 231
| Name| Type                         | Mandatory| Description                    |
| ------ | ----------------------------- | ---- | ------------------------ |
S
shawn_he 已提交
232
| config | [ConfigOption](#configoption) | Yes  | Configuration items for application event logging.|
Z
zengyawen 已提交
233

S
shawn_he 已提交
234 235
**Return value**

S
shawn_he 已提交
236 237
| Type   | Description                                                       |
| ------- | ----------------------------------------------------------- |
S
shawn_he 已提交
238
| boolean | Returns **true** if the configuration is successful; returns **false** otherwise.|
S
shawn_he 已提交
239 240

**Example**
S
shawn_he 已提交
241

L
lyj_love_code 已提交
242
```js
S
shawn_he 已提交
243 244 245 246 247 248 249 250 251 252
// Set the application event logging switch.
hiAppEvent.configure({
    disable: true
});

// Configure the maximum size of the directory that stores the event logging files.
hiAppEvent.configure({
    maxStorage: '100M'
});
```
Z
zengyawen 已提交
253

S
shawn_he 已提交
254
## ConfigOption
Z
zengyawen 已提交
255 256 257

Provides the configuration items for application event logging.

S
shawn_he 已提交
258 259 260 261
**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name    | Type   | Mandatory| Description                                                        |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
| disable    | boolean | No  | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.|
| maxStorage | string  | No  | Maximum size of the event file storage directory. The default value is <strong>10M</strong>. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|

## hiAppEvent.addWatcher<sup>9+</sup>

addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9)

Adds an event watcher.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

**Parameters**

| Name | Type                | Mandatory| Description            |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher9) | Yes  | Event watcher.|

**Return value**

| Type                                            | Description                                |
| ------------------------------------------------ | ------------------------------------ |
| [AppEventPackageHolder](#appeventpackageholder9) | Subscription data holder. If the subscription fails, **null** will be returned.|

**Example**

```js
// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
hiAppEvent.addWatcher({
    name: "watcher1",
    appEventFilters: [
        {
            domain: "domain_test1",
            eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
        }
    ],
    triggerCondition: {
        row: 10,
        size: 1000,
        timeOut: 1
    },
    onTrigger: function (curRow, curSize, holder) {
        if (holder == null) {
            console.error("holder is null");
            return;
        }
S
shawn_he 已提交
307 308
        let eventPkg = null;
        while ((eventPkg = holder.takeNext()) != null) {
S
shawn_he 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            console.info("eventPkg.packageId=" + eventPkg.packageId);
            console.info("eventPkg.row=" + eventPkg.row);
            console.info("eventPkg.size=" + eventPkg.size);
            for (const eventInfo of eventPkg.data) {
                console.info("eventPkg.data=" + eventInfo);
            }
        }
    }
});

// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
let holder = hiAppEvent.addWatcher({
    name: "watcher2",
});
if (holder != null) {
S
shawn_he 已提交
324 325 326 327 328 329 330 331
    let eventPkg = null;
    while ((eventPkg = holder.takeNext()) != null) {
        console.info("eventPkg.packageId=" + eventPkg.packageId);
        console.info("eventPkg.row=" + eventPkg.row);
        console.info("eventPkg.size=" + eventPkg.size);
        for (const eventInfo of eventPkg.data) {
            console.info("eventPkg.data=" + eventInfo);
        }
S
shawn_he 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    }
}
```

## hiAppEvent.removeWatcher<sup>9+</sup>

removeWatcher(watcher: [Watcher](#watcher9)): void

Removes an event watcher.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

**Parameters**

| Name | Type                | Mandatory| Description            |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher9) | Yes  | Event watcher.|

**Example**

```js
// 1. Define a watcher.
let watcher = {
    name: "watcher1",
}

// 2. Add the watcher to subscribe to application events.
hiAppEvent.addWatcher(watcher);

// 3. Remove the watcher to unsubscribe from application events.
hiAppEvent.removeWatcher(watcher);
```

## Watcher<sup>9+</sup>

Defines parameters for a **Watcher** object.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name            | Type                                                    | Mandatory| Description                            |
| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- |
| name             | string                                                       | Yes  | Unique watcher name.|
| triggerCondition | [TriggerCondition](#triggercondition9)                       | No  | Subscription callback trigger condition.              |
| appEventFilters  | [AppEventFilter](#appeventfilter9)[]                         | No  | Application event filter criteria.                  |
| onTrigger        | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | No  | Subscription callback.                 |

## TriggerCondition<sup>9+</sup>

Defines parameters for a **TriggerCondition** object.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name   | Type| Mandatory| Description                                  |
| ------- | -------- | ---- | -------------------------------------- |
| row     | number   | No  | Number of events.              |
| size    | number   | No  | Event data size, in bytes.|
| timeOut | number   | No  | Timeout interval, in unit of 30s.   |

## AppEventFilter<sup>9+</sup>

Defines parameters for an **AppEventFilter** object.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name      | Type                 | Mandatory| Description                    |
| ---------- | ------------------------- | ---- | ------------------------ |
| domain     | string                    | Yes  | Event domain.    |
| eventTypes | [EventType](#eventtype)[] | No  | Event types.|

## AppEventPackageHolder<sup>9+</sup>

Defines a subscription data holder for processing subscription events.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

### setSize<sup>9+</sup>

setSize(size: number): void

Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes.

**Example**

```js
S
shawn_he 已提交
416 417 418
let holder = hiAppEvent.addWatcher({
    name: "watcher",
});
S
shawn_he 已提交
419 420 421 422 423 424 425 426 427 428 429 430
holder.setSize(1000);
```

### takeNext<sup>9+</sup>

takeNext(): [AppEventPackage](#appeventpackage9)

Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.

**Example**

```js
S
shawn_he 已提交
431 432 433
let holder = hiAppEvent.addWatcher({
    name: "watcher",
});
S
shawn_he 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
let eventPkg = holder.takeNext();
```

## AppEventPackage<sup>9+</sup>

Defines parameters for an **AppEventPackage** object.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name     | Type| Description                          |
| --------- | -------- | ------------------------------ |
| packageId | number   | Event package ID, which is named from **0** in ascending order.   |
| row       | number   | Number of events in the event package.            |
| size      | number   | Data size of the event package, in bytes.|
| data      | string[] | Event data in the event package.            |

## hiAppEvent.clearData<sup>9+</sup>

clearData(): void

Clears local logging data.

**System capability**: SystemCapability.HiviewDFX.HiAppEvent

**Example**

```js
hiAppEvent.clearData();
```
S
shawn_he 已提交
463 464 465


## EventType
Z
zengyawen 已提交
466 467 468

Enumerates event types.

S
shawn_he 已提交
469 470 471 472
**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name     | Default Value| Description          |
| --------- | ------ | -------------- |
S
shawn_he 已提交
473 474 475 476
| FAULT     | 1      | Fault event.|
| STATISTIC | 2      | Statistical event.|
| SECURITY  | 3      | Security event.|
| BEHAVIOR  | 4      | Behavior event.|
S
shawn_he 已提交
477 478 479


## Event
Z
zengyawen 已提交
480 481 482

Provides constants that define the names of all predefined events.

S
shawn_he 已提交
483 484 485 486 487 488
**System capability**: SystemCapability.HiviewDFX.HiAppEvent

| Name                     | Type| Readable| Writable| Description                |
| ------------------------- | -------- | ---- | ---- | -------------------- |
| USER_LOGIN                | string   | Yes  | No  | User login event.      |
| USER_LOGOUT               | string   | Yes  | No  | User logout event.      |
S
shawn_he 已提交
489
| DISTRIBUTED_SERVICE_START | string   | Yes  | No  | Distributed service startup event.|
Z
zengyawen 已提交
490 491


S
shawn_he 已提交
492 493 494
## Param

Provides constants that define the names of all predefined event parameters.
Z
zengyawen 已提交
495

S
shawn_he 已提交
496 497
**System capability**: SystemCapability.HiviewDFX.HiAppEvent

S
shawn_he 已提交
498
| Name                           | Type| Readable| Writable| Description              |
S
shawn_he 已提交
499 500
| ------------------------------- | -------- | ---- | ---- | ------------------ |
| USER_ID                         | string   | Yes  | No  | Custom user ID.    |
S
shawn_he 已提交
501 502
| DISTRIBUTED_SERVICE_NAME        | string   | Yes  | No  | Distributed service name.  |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string   | Yes  | No  | Distributed service instance ID.|