js-apis-hiviewdfx-hiappevent.md 18.2 KB
Newer Older
S
shawn_he 已提交
1
# @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
S
shawn_he 已提交
2

S
shawn_he 已提交
3
The **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.
S
shawn_he 已提交
4

S
shawn_he 已提交
5 6
> **NOTE**
>
S
shawn_he 已提交
7 8 9 10 11 12 13 14 15 16 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
> 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.


## Modules to Import

```js
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
```

## hiAppEvent.write

write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback<void>): void

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

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

**Parameters**

| Name  | Type                          | Mandatory| Description          |
| -------- | ------------------------------ | ---- | -------------- |
| info     | [AppEventInfo](#appeventinfo) | Yes  | Application event object.|
| callback | AsyncCallback<void>      | Yes  | Callback used to return the result.|

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message                                     |
| -------- | --------------------------------------------- |
| 11100001 | Function is disabled.                         |
| 11101001 | Invalid event domain.                         |
| 11101002 | Invalid event name.                           |
| 11101003 | Invalid number of event parameters.           |
| 11101004 | Invalid string length of the event parameter. |
| 11101005 | Invalid event parameter name.                 |
| 11101006 | Invalid array length of the event parameter.  |

**Example**

```js
hiAppEvent.write({
    domain: "test_domain",
    name: "test_event",
    eventType: hiAppEvent.EventType.FAULT,
    params: {
        int_data: 100,
        str_data: "strValue"
    }
}, (err) => {
    if (err) {
        console.error(`code: ${err.code}, message: ${err.message}`);
        return;
    }
    console.log(`success to write event`);
});
```

## hiAppEvent.write

write(info: [AppEventInfo](#appeventinfo)): Promise<void>

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

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

**Parameters**

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

**Return value**

| Type               | Description         |
| ------------------- | ------------- |
| Promise<void> | Promise used to return the result.|

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message                                     |
| -------- | --------------------------------------------- |
| 11100001 | Function is disabled.                         |
| 11101001 | Invalid event domain.                         |
| 11101002 | Invalid event name.                           |
| 11101003 | Invalid number of event parameters.           |
| 11101004 | Invalid string length of the event parameter. |
| 11101005 | Invalid event parameter name.                 |
| 11101006 | Invalid array length of the event parameter.  |

**Example**

```js
hiAppEvent.write({
    domain: "test_domain",
    name: "test_event",
    eventType: hiAppEvent.EventType.FAULT,
    params: {
        int_data: 100,
        str_data: "strValue"
    }
}).then(() => {
    console.log(`success to write event`);
}).catch((err) => {
    console.error(`code: ${err.code}, message: ${err.message}`);
});
```

## AppEventInfo

Defines parameters for an **AppEventInfo** object.

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

S
shawn_he 已提交
123 124 125 126 127 128
| Name     | Type                   | Mandatory| Description                                                        |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| 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 (_).|
| 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 (_).|
| eventType | [EventType](#eventtype) | Yes  | Event type.                                                  |
| 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.|
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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

## hiAppEvent.configure

configure(config: [ConfigOption](configoption)): void

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.

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

**Parameters**

| Name| Type                         | Mandatory| Description                    |
| ------ | ----------------------------- | ---- | ------------------------ |
| config | [ConfigOption](#configoption) | Yes  | Configuration items for application event logging.|

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message                        |
| -------- | -------------------------------- |
| 11103001 | Invalid max storage quota value. |

**Example**

```js
// Disable the event logging function.
hiAppEvent.configure({
    disable: true
});

// Set the maximum size of the file storage directory to 100 MB.
hiAppEvent.configure({
    maxStorage: '100M'
});
```

## ConfigOption

Configures options for application event logging.

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

| Name      | Type   | Mandatory| Description                                                        |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
| 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.|
| 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.|

## hiAppEvent.addWatcher

addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpackageholder)

Adds a watcher to subscribe to application events.

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

**Parameters**

| Name | Type                | Mandatory| Description            |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher) | Yes  | Watcher for application events.|

**Return value**

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

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message                       |
| -------- | ------------------------------- |
| 11102001 | Invalid watcher name.           |
| 11102002 | Invalid filtering event domain. |
| 11102003 | Invalid row value.              |
| 11102004 | Invalid size value.             |
| 11102005 | Invalid timeout value.          |

**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: "test_domain",
            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;
        }
        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}`);
            }
        }
    }
});

// 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) {
    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}`);
        }
    }
}
```

## hiAppEvent.removeWatcher

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

Removes a watcher to unsubscribe from application events.

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

**Parameters**

| Name | Type                | Mandatory| Description            |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher) | Yes  | Watcher for application events.|

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message             |
| -------- | --------------------- |
| 11102001 | Invalid watcher name. |

**Example**

```js
// 1. Define a watcher for application events.
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

Defines parameters for a **Watcher** object.

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

| Name            | Type                                                        | Mandatory| Description                                                        |
| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| name             | string                                                       | Yes  | Unique name of the watcher.                            |
| triggerCondition | [TriggerCondition](#triggercondition)                        | No  | Subscription callback triggering condition. This parameter takes effect only when it is passed together with the callback.          |
| appEventFilters  | [AppEventFilter](#appeventfilter)[]                          | No  | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered.              |
| 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.|

## TriggerCondition

Defines callback triggering conditions. Subscription callback is triggered when any condition is met.

**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

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

Defines a subscription data holder for processing subscription events.

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

### constructor

constructor(watcherName: string)

Constructor 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.

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

**Parameters**

| Name| Type             | Mandatory| Description                    |
| ------ | ----------------- | ---- | ------------------------ |
| watcherName | string | Yes  | Watcher name.|

**Example**

```js
let holder = hiAppEvent.addWatcher({
    name: "watcher",
});
```

### setSize

setSize(size: number): void

Sets the threshold for the data size of the application event package obtained each time.

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

**Parameters**

| Name| Type  | Mandatory| Description                                        |
| ------ | ------ | ---- | -------------------------------------------- |
| size   | number | Yes  | Data size threshold, in bytes. The default value is **512*1024**.|

**Error codes**

For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).

| ID| Error Message           |
| -------- | ------------------- |
| 11104001 | Invalid size value. |

**Example**

```js
let holder = hiAppEvent.addWatcher({
    name: "watcher",
});
holder.setSize(1000);
```

### takeNext

takeNext(): [AppEventPackage](#appeventpackage)

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

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

**Example**

```js
let holder = hiAppEvent.addWatcher({
    name: "watcher",
});
let eventPkg = holder.takeNext();
```

## AppEventPackage

Defines parameters for an **AppEventPackage** object.

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

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

## hiAppEvent.clearData

clearData(): void

Clears local application event logging data.

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

**Example**

```js
hiAppEvent.clearData();
```


## EventType

Enumerates event types.

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

| Name     | Value  | Description          |
| --------- | ---- | -------------- |
| FAULT     | 1    | Fault event.|
| STATISTIC | 2    | Statistical event.|
| SECURITY  | 3    | Security event.|
| BEHAVIOR  | 4    | Behavior event.|


S
shawn_he 已提交
451
## event
S
shawn_he 已提交
452 453 454 455 456

Provides constants that define the names of all predefined events.

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

S
shawn_he 已提交
457 458 459 460 461
| Name                     | Type  | Description                |
| ------------------------- | ------ | -------------------- |
| USER_LOGIN                | string | User login event.      |
| USER_LOGOUT               | string | User logout event.      |
| DISTRIBUTED_SERVICE_START | string | Distributed service startup event.|
S
shawn_he 已提交
462 463


S
shawn_he 已提交
464
## param
S
shawn_he 已提交
465 466 467 468 469

Provides constants that define the names of all predefined event parameters.

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

S
shawn_he 已提交
470 471 472 473 474
| Name                           | Type  | Description              |
| ------------------------------- | ------ | ------------------ |
| USER_ID                         | string | Custom user ID.    |
| DISTRIBUTED_SERVICE_NAME        | string | Distributed service name.  |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID.|