• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.hiSysEvent (System Event Logging)
2
3The **hiSysEvent** module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file.
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> - The APIs provided by this module are system APIs.
9
10
11## Modules to Import
12
13```ts
14import hiSysEvent from '@ohos.hiSysEvent';
15```
16
17## EventType
18
19Enumerates event types.
20
21**System capability**: SystemCapability.HiviewDFX.HiSysEvent
22
23| Name| Value| Description|
24| -------- | -------- | -------- |
25| FAULT | 1 | Error event.|
26| STATISTIC | 2 | Statistic event.|
27| SECURITY | 3 | Security event.|
28| BEHAVIOR | 4 | User behavior event.|
29
30## SysEventInfo
31
32Defines a system event.
33
34**System capability**: SystemCapability.HiviewDFX.HiSysEvent
35
36| Name| Type| Mandatory| Description|
37| -------- | -------- | -------- | -------- |
38| domain | string | Yes| Event domain.|
39| name | string | Yes| Event name.|
40| eventType | [EventType](#eventtype) | Yes| Event type.|
41| params | object | No| Event parameters.|
42
43
44## hiSysEvent.write
45
46write(info: SysEventInfo, callback: AsyncCallback<void>): void
47
48Writes event information to the event file. This API uses an asynchronous callback to return the result.
49
50**System capability**: SystemCapability.HiviewDFX.HiSysEvent
51
52**Parameters**
53
54| Name   | Type                     | Mandatory| Description                                                        |
55| --------- | ------------------------- | ---- | ------------------------------------------------------------ |
56| info | [SysEventInfo](#syseventinfo) | Yes| System event information.|
57| callback  | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.<br>- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously. <br>- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.<br>- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.|
58
59**Error codes**
60
61For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
62
63| ID| Error Message|
64| ------- | ----------------------------------------------------------------- |
65| 11200001 | Invalid event domain.                                            |
66| 11200002 | Invalid event name.                                              |
67| 11200003 | Abnormal environment.                                            |
68| 11200004 | Length of the event is over limit.                               |
69| 11200051 | Invalid event parameter.                                         |
70| 11200052 | Size of the event parameter of the string type is over limit.    |
71| 11200053 | Count of event parameters is over limit.                         |
72| 11200054 | Count of event parameter of the array type is over limit.        |
73
74**Example**
75
76```ts
77import hiSysEvent from '@ohos.hiSysEvent';
78import { BusinessError } from '@ohos.base';
79
80try {
81  let customizedParams: Record<string, string | number> = {
82    'PID': 487,
83    'UID': 103,
84    'PACKAGE_NAME': "com.ohos.hisysevent.test",
85    'PROCESS_NAME': "syseventservice",
86    'MSG': "no msg."
87  };
88  let eventInfo: hiSysEvent.SysEventInfo = {
89    domain: "RELIABILITY",
90    name: "STACK",
91    eventType: hiSysEvent.EventType.FAULT,
92    params: customizedParams
93  };
94  hiSysEvent.write(eventInfo, (err: BusinessError) => {
95    // do something here.
96  });
97} catch (err) {
98  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
99}
100```
101
102
103## hiSysEvent.write
104
105write(info: SysEventInfo): Promise&lt;void&gt;
106
107Writes event information to the event file. This API uses a promise to return the result.
108
109**System capability**: SystemCapability.HiviewDFX.HiSysEvent
110
111**Parameters**
112
113| Name   | Type                   | Mandatory| Description|
114| --------- | ----------------------- | ---- | --------------- |
115| info | [SysEventInfo](#syseventinfo) | Yes  | System event information.|
116
117**Return value**
118
119| Type               | Description                                                        |
120| ------------------- | ------------------------------------------------------------ |
121| Promise&lt;void&gt; | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.|
122
123**Error codes**
124
125For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
126
127| ID| Error Message|
128| -------- | ---------------------------------------------------------------- |
129| 11200001 | Invalid event domain.                                            |
130| 11200002 | Invalid event name.                                              |
131| 11200003 | Abnormal environment.                                            |
132| 11200004 | Length of the event is over limit.                               |
133| 11200051 | Invalid event parameter.                                         |
134| 11200052 | Size of the event parameter of the string type is over limit.    |
135| 11200053 | Count of event parameters is over limit.                         |
136| 11200054 | Count of event parameter of the array type is over limit.        |
137
138**Example**
139
140```ts
141import hiSysEvent from '@ohos.hiSysEvent';
142import { BusinessError } from '@ohos.base';
143
144try {
145  let customizedParams: Record<string, string | number> = {
146    'PID': 487,
147    'UID': 103,
148    'PACKAGE_NAME': "com.ohos.hisysevent.test",
149    'PROCESS_NAME': "syseventservice",
150    'MSG': "no msg."
151  };
152  let eventInfo: hiSysEvent.SysEventInfo = {
153    domain: "RELIABILITY",
154    name: "STACK",
155    eventType: hiSysEvent.EventType.FAULT,
156    params: customizedParams
157  };
158  hiSysEvent.write(eventInfo).then(
159    () => {
160      // do something here.
161    }
162  ).catch(
163    (err: BusinessError) => {
164      console.error(`error code: ${err.code}, error msg: ${err.message}`);
165    }
166  );
167} catch (err) {
168  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
169}
170```
171
172## RuleType
173
174Enumerates matching rule types.
175
176**System capability**: SystemCapability.HiviewDFX.HiSysEvent
177
178| Name| Value| Description|
179| -------- | -------- | -------- |
180| WHOLE_WORD | 1 | Whole word matching.|
181| PREFIX | 2 | Prefix matching.|
182| REGULAR | 3 | Regular expression matching.|
183
184## WatchRule
185
186Defines event subscription rules.
187
188**System capability**: SystemCapability.HiviewDFX.HiSysEvent
189
190| Name| Type| Mandatory| Description|
191| -------- | -------- | -------- | -------- |
192| domain | string | Yes| Event domain.|
193| name | string | Yes| Event name.|
194| tag | string | No| Event tag.|
195| ruleType | [RuleType](#ruletype) | Yes| Matching rule type.|
196
197## Watcher
198
199Defines a watcher for event subscription.
200
201**System capability**: SystemCapability.HiviewDFX.HiSysEvent
202
203| Name| Type| Mandatory| Description|
204| -------- | -------- | -------- | -------- |
205| rules | [WatchRule](#watchrule)[] | Yes| Array of matching event subscription rules.|
206| onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void|
207| onServiceDied | function | Yes| Callback for disabling of event subscription: () => void|
208
209## hiSysEvent.addWatcher
210
211addWatcher(watcher: Watcher): void
212
213Adds a watcher for event subscription.
214
215**Required permission**: ohos.permission.READ_DFX_SYSEVENT
216
217**System capability**: SystemCapability.HiviewDFX.HiSysEvent
218
219**Parameters**
220
221| Name| Type| Mandatory| Description|
222| ------ | ----------------------------- | ---- | ------------------------ |
223| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
224
225**Error codes**
226
227For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
228
229| ID| Error Message|
230| -------- | ----------------------------------- |
231| 11200101 | Count of watchers is over limit.    |
232| 11200102 | Count of watch rules is over limit. |
233
234**Example**
235
236```ts
237import hiSysEvent from '@ohos.hiSysEvent';
238import { BusinessError } from '@ohos.base';
239
240let watchRules: hiSysEvent.WatchRule[] = [{
241    domain: "RELIABILITY",
242    name: "STACK",
243    tag: "STABILITY",
244    ruleType: hiSysEvent.RuleType.WHOLE_WORD,
245  } as hiSysEvent.WatchRule];
246let watcher: hiSysEvent.Watcher = {
247  rules: watchRules,
248  onEvent: (info: hiSysEvent.SysEventInfo) => {
249    // do something here.
250  },
251  onServiceDied: () => {
252    // do something here.
253  }
254};
255try {
256  hiSysEvent.addWatcher(watcher);
257} catch (err) {
258  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
259}
260```
261
262## hiSysEvent.removeWatcher
263
264removeWatcher(watcher: Watcher): void
265
266Removes a watcher used for event subscription.
267
268**Required permission**: ohos.permission.READ_DFX_SYSEVENT
269
270**System capability**: SystemCapability.HiviewDFX.HiSysEvent
271
272**Parameters**
273
274| Name| Type | Mandatory| Description |
275| ------ | ------------- | ---- | ------------------------- |
276| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
277
278**Error codes**
279
280For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
281
282| ID| Error Message|
283| -------- | --------------------------- |
284| 11200201 | The watcher does not exist. |
285
286**Example**
287
288```ts
289import hiSysEvent from '@ohos.hiSysEvent';
290import { BusinessError } from '@ohos.base';
291
292let watchRules: hiSysEvent.WatchRule[] = [{
293    domain: "RELIABILITY",
294    name: "STACK",
295    tag: "STABILITY",
296    ruleType: hiSysEvent.RuleType.WHOLE_WORD,
297  } as hiSysEvent.WatchRule ];
298let watcher: hiSysEvent.Watcher = {
299  rules: watchRules,
300  onEvent: (info: hiSysEvent.SysEventInfo) => {
301    // do something here.
302  },
303  onServiceDied: () => {
304    // do something here.
305  }
306};
307try {
308  hiSysEvent.addWatcher(watcher);
309  hiSysEvent.removeWatcher(watcher);
310} catch (err) {
311  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
312}
313```
314
315## QueryArg
316
317Defines arguments for an event query.
318
319**System capability**: SystemCapability.HiviewDFX.HiSysEvent
320
321| Name| Type| Mandatory| Description|
322| -------- | -------- | -------- | -------- |
323| beginTime | number | Yes| Start time (13-digit timestamp) for the event query.|
324| endTime | number | Yes| End time (13-digit timestamp) for the event query.|
325| maxEvents | number | Yes| Maximum number of events that can be queried.|
326| fromSeq<sup>10+</sup> | number | No  | Start SN of the events to be queried. The default value is **-1**.|
327| toSeq<sup>10+</sup> | number | No  | End SN of the system events to be queried. The default value is **-1**.|
328
329## QueryRule
330
331Defines event query rules.
332
333**System capability**: SystemCapability.HiviewDFX.HiSysEvent
334
335| Name| Type| Mandatory| Description|
336| -------- | -------- | -------- | -------- |
337| domain | string | Yes| Event domain.|
338| names | string[] | Yes| Array of event names. A **QueryRule** object contains multiple system event names.|
339| condition<sup>10+</sup> | string | No| Additional event conditions. The value of this parameter is in the format of {"version":"V1","condition":{"and":[{"param":"*Parameter*","op":"*Operator*","value":"*Comparison value*"}]}}.|
340
341## Querier
342
343Defines an event query instance.
344
345**System capability**: SystemCapability.HiviewDFX.HiSysEvent
346
347| Name| Type| Mandatory| Description|
348| -------- | -------- | -------- | -------- |
349| onQuery | function | Yes| Callback used to return the queried system events: (infos: [SysEventInfo](#syseventinfo)[]) => void.|
350| onComplete | function | Yes| Callback used to return the query result statistics: (reason: number, total: number) => void|
351
352## hiSysEvent.query
353
354query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): void
355
356Queries system events.
357
358**Required permission**: ohos.permission.READ_DFX_SYSEVENT
359
360**System capability**: SystemCapability.HiviewDFX.HiSysEvent
361
362**Parameters**
363
364| Name| Type| Mandatory| Description|
365| ------ | ----------------------------- | ---- | ------------------------ |
366| queryArg | [QueryArg](#queryarg) | Yes  | Arguments for event query.|
367| rules | [QueryRule](#queryrule)[] | Yes  | Array of event query rules.|
368| querier | [Querier](#querier) | Yes  | Event query instance.|
369
370**Error codes**
371
372For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
373
374| ID| Error Message|
375| -------- | ------------------------------------------- |
376| 11200301 | Count of query rules is over limit.         |
377| 11200302 | Invalid query rule.                         |
378| 11200303 | Count of concurrent queriers is over limit. |
379| 11200304 | Query frequency is over limit.              |
380
381**Example**
382
383```ts
384import hiSysEvent from '@ohos.hiSysEvent';
385import { BusinessError } from '@ohos.base';
386
387try {
388  let customizedParams: Record<string, string | number> = {
389    'PID': 487,
390    'UID': 103,
391    'PACKAGE_NAME': "com.ohos.hisysevent.test",
392    'PROCESS_NAME': "syseventservice",
393    'MSG': "no msg."
394  };
395  let eventInfo: hiSysEvent.SysEventInfo = {
396    domain: "RELIABILITY",
397    name: "STACK",
398    eventType: hiSysEvent.EventType.FAULT,
399    params: customizedParams
400  };
401  hiSysEvent.write(eventInfo, (err: BusinessError) => {
402    // do something here.
403  });
404
405  let queryArg: hiSysEvent.QueryArg = {
406    beginTime: -1,
407    endTime: -1,
408    maxEvents: 5,
409  };
410  let queryRules: hiSysEvent.QueryRule[] = [{
411    domain: "RELIABILITY",
412    names: ["STACK"],
413  } as hiSysEvent.QueryRule];
414  let querier: hiSysEvent.Querier = {
415    onQuery: (infos: hiSysEvent.SysEventInfo[]) => {
416      // do something here.
417    },
418    onComplete: (reason: number, total: number) => {
419      // do something here.
420    }
421  };
422  hiSysEvent.query(queryArg, queryRules, querier);
423} catch (err) {
424  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
425}
426```
427
428## hiSysEvent.exportSysEvents<sup>10+</sup>
429
430exportSysEvents(queryArg: QueryArg, rules: QueryRule[]): number
431
432Exports system events in batches and writes them as a file to the fixed directory of the application sandbox (that is, **/data/storage/el2/base/cache/hiview/event/**).
433
434**Required permission**: ohos.permission.READ_DFX_SYSEVENT
435
436**System capability**: SystemCapability.HiviewDFX.HiSysEvent
437
438**Parameters**
439
440| Name  | Type                     | Mandatory| Description                                      |
441| -------- | ------------------------- | ---- | ------------------------------------------ |
442| queryArg | [QueryArg](#queryarg)     | Yes  | Event query parameters for the export.                  |
443| rules    | [QueryRule](#queryrule)[] | Yes  | Array of event query rules for the export.|
444
445**Return value**
446
447| Type  | Description            |
448| ------ | ---------------- |
449| number | API call timestamp.|
450
451**Error codes**
452
453For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
454
455| ID| Error Message                           |
456| -------- | ----------------------------------- |
457| 11200301 | Count of query rules is over limit. |
458| 11200302 | Invalid query rule.                 |
459| 11200304 | Export frequency is over limit.     |
460
461**Example**
462
463```ts
464import hiSysEvent from '@ohos.hiSysEvent';
465import fs from '@ohos.file.fs';
466import { BusinessError } from '@ohos.base';
467
468try {
469  let customizedParams: Record<string, string | number> = {
470    'PID': 487,
471    'UID': 103,
472    'PACKAGE_NAME': "com.ohos.hisysevent.test",
473    'PROCESS_NAME': "syseventservice",
474    'MSG': "no msg."
475  };
476  let eventInfo: hiSysEvent.SysEventInfo = {
477    domain: "RELIABILITY",
478    name: "STACK",
479    eventType: hiSysEvent.EventType.FAULT,
480    params: customizedParams
481  };
482  hiSysEvent.write(eventInfo, (err: BusinessError) => {
483    // do something here.
484  });
485
486  let queryArg: hiSysEvent.QueryArg = {
487    beginTime: -1,
488    endTime: -1,
489    maxEvents: 1,
490  };
491  let queryRules: hiSysEvent.QueryRule[] = [{
492    domain: "RELIABILITY",
493    names: ["STACK"],
494  } as hiSysEvent.QueryRule];
495  let time = hiSysEvent.exportSysEvents(queryArg, queryRules);
496  console.log(`receive export task time is : ${time}`);
497
498  // Postpone reading of exported events.
499  setTimeout(() => {
500    let eventDir = '/data/storage/el2/base/cache/hiview/event';
501    let filenames = fs.listFileSync(eventDir);
502    for (let i = 0; i < filenames.length; i++) {
503      if (filenames[i].indexOf(time.toString()) != -1) {
504        let res = fs.readTextSync(eventDir + '/' + filenames[i]);
505        let events: string = JSON.parse('[' + res.slice(0, res.length - 1) + ']');
506        console.log("read file end, events is :" + JSON.stringify(events));
507      }
508    }
509  }, 10000);
510} catch (err) {
511  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
512}
513```
514
515## hiSysEvent.subscribe<sup>10+</sup>
516
517subscribe(rules: QueryRule[]): number
518
519Subscribes to real-time system events that occur occasionally or occur in a low frequency. These events are written as a file to the fixed directory of the application sandbox (that is, **/data/storage/el2/base/cache/hiview/event/**).
520
521**Required permission**: ohos.permission.READ_DFX_SYSEVENT
522
523**System capability**: SystemCapability.HiviewDFX.HiSysEvent
524
525**Parameters**
526
527| Name| Type                     | Mandatory| Description                                      |
528| ------ | ------------------------- | ---- | ------------------------------------------ |
529| rules  | [QueryRule](#queryrule)[] | Yes  | Array of event query rules for the subscription.|
530
531**Return value**
532
533| Type  | Description            |
534| ------ | ---------------- |
535| number | API call timestamp.|
536
537**Error codes**
538
539For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
540
541| ID| Error Message                           |
542| -------- | ----------------------------------- |
543| 11200301 | Count of query rules is over limit. |
544| 11200302 | Invalid query rule.                 |
545
546**Example**
547
548```ts
549import hiSysEvent from '@ohos.hiSysEvent';
550import fs from '@ohos.file.fs';
551import { BusinessError } from '@ohos.base';
552
553try {
554  let rules: hiSysEvent.QueryRule[] = [{
555    domain: "RELIABILITY",
556    names: ["STACK"],
557  } as hiSysEvent.QueryRule,
558  {
559    domain: "BUNDLE_MANAGER",
560    names: ["BUNDLE_UNINSTALL"],
561  } as hiSysEvent.QueryRule];
562  hiSysEvent.subscribe(rules);
563
564  let customizedParams: Record<string, string | number> = {
565    'PID': 487,
566    'UID': 103,
567    'PACKAGE_NAME': "com.ohos.hisysevent.test",
568    'PROCESS_NAME': "syseventservice",
569    'MSG': "no msg."
570  };
571  let eventInfo: hiSysEvent.SysEventInfo = {
572    domain: "RELIABILITY",
573    name: "STACK",
574    eventType: hiSysEvent.EventType.FAULT,
575    params: customizedParams
576  };
577  hiSysEvent.write(eventInfo, (err: BusinessError) => {
578    // do something here.
579  });
580
581  // Postpone reading of subscribed events.
582  setTimeout(() => {
583    let eventDir = '/data/storage/el2/base/cache/hiview/event';
584    let filenames = fs.listFileSync(eventDir);
585    for (let i = 0; i < filenames.length; i++) {
586      let res = fs.readTextSync(eventDir + '/' + filenames[i]);
587      let events: string = JSON.parse('[' + res.slice(0, res.length - 1) + ']');
588      console.log("read file end, events is :" + JSON.stringify(events));
589    }
590  }, 10000);
591} catch (err) {
592  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
593}
594```
595
596## hiSysEvent.unsubscribe<sup>10+</sup>
597
598unsubscribe(): void
599
600Unsubscribes from system events.
601
602**Required permission**: ohos.permission.READ_DFX_SYSEVENT
603
604**System capability**: SystemCapability.HiviewDFX.HiSysEvent
605
606**Error codes**
607
608For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
609
610| ID| Error Message           |
611| -------- | ------------------- |
612| 11200305 | Unsubscribe failed. |
613
614**Example**
615
616```ts
617import hiSysEvent from '@ohos.hiSysEvent';
618import { BusinessError } from '@ohos.base';
619
620try {
621  let rules: hiSysEvent.QueryRule[] = [{
622    domain: "RELIABILITY",
623    names: ["STACK"],
624  } as hiSysEvent.QueryRule,
625  {
626    domain: "BUNDLE_MANAGER",
627    names: ["BUNDLE_UNINSTALL"],
628  } as hiSysEvent.QueryRule];
629  hiSysEvent.subscribe(rules);
630  hiSysEvent.unsubscribe();
631} catch (err) {
632  console.error(`error code: ${(err as BusinessError).code}, error msg: ${(err as BusinessError).message}`);
633}
634```
635