1# HiSysEvent Listening
2
3
4## Overview
5
6
7### Function Introduction
8
9HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to subscribe to power consumption events for power usage analysis.
10
11
12### Constraints
13
14Before listening for system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
15
16
17## How to Develop
18
19### Available APIs
20
21#### C++ APIs
22
23HiSysEvent is implemented using the APIs provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
24
25> **NOTE**
26>
27> For details about the **RuleType** argument in the constructor of **ListenerRule**, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
28
29  **Table 1** Description of C++ HiSysEventManager APIs
30
31| Name| Description|
32| -------- | -------- |
33| int32_t&nbsp;HiSysEventManager::AddListener(std::shared_ptr&lt;HiSysEventListener&gt;&nbsp;listener,<br>&nbsp;std::vector&lt;ListenerRule&gt;&amp;&nbsp;rules) | Adds a listener to listen for system events based on the specified rules.<br>Input arguments:<br>- **listener**: listener for system events.<br>- **rules**: event listening rules.<br>Return value:<br>- **0**: The listener is added successfully.<br>- A negative value: The listener fails to be added.|
34| int32_t&nbsp;HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventListener&gt;&nbsp;listener) | Removes the listener for system events.<br>Input arguments:<br>- **listener**: listener for system events.<br>Return value:<br>- **0**: The listener is removed successfully.<br>- A negative value: The listener fails to be removed. |
35
36  **Table 2** Description of ListenerRule
37
38| Name| Description|
39| -------- | -------- |
40| ListenerRule(const&nbsp;std::string&amp;&nbsp;tag,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
41| ListenerRule(const&nbsp;std::string&amp;&nbsp;domain,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;eventName,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.<br>Input arguments:<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
42| ListenerRule(const&nbsp;std::string&amp;&nbsp;domain,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;eventName,<br>&nbsp;const&nbsp;std::string&amp;&nbsp;tag,<br>&nbsp;RuleType&nbsp;ruleType&nbsp;=&nbsp;RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.<br>Input arguments:<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
43
44  **Table 3** Description of HiSysEventListener
45
46| Name| Description|
47| -------- | -------- |
48| void&nbsp;HiSysEventListener::OnEvent(std::shared_ptr&lt;HiSysEventRecord&gt;&nbsp;sysEvent) | Callback object for system events.<br>Input arguments:<br>- **sysEvent**: real-time system event.<br>Return value:<br>None.|
49| void&nbsp;HiSysEventListener::OnServiceDied() | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None.|
50
51  **Table 4** Description of HiSysEventRecord
52| Name| Description|
53| -------- | -------- |
54|std::string&nbsp;HiSysEventRecord::AsJson()|Obtains the content of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Content of the system event.|
55|std::string&nbsp;HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Domain name of the system event.|
56|std::string&nbsp;HiSysEventRecord::GetEventName()|Obtains the name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Name of the system event.|
57|HiSysEvent::EventType&nbsp;HiSysEventRecord::GetEventType()|Obtains the type of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Type of the system event.|
58|std::string&nbsp;HiSysEventRecord::GetLevel()|Obtains the level of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Level of the system event.|
59|std::string&nbsp;HiSysEventRecord::GetTag()|Obtains the tag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Tag of the system event.|
60|std::string&nbsp;HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Time zone, in the format of **+0800**.|
61|int&nbsp;HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Distributed call chain tracing flag.|
62|int64_t&nbsp;HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Process ID.|
63|int64_t&nbsp;HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Thread ID.|
64|int64_t&nbsp;HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>User ID.|
65|uint64_t&nbsp;HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Parent span ID of the distributed call chain tracing task.|
66|uint64_t&nbsp;HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Span ID of the distributed call chain tracing task.|
67|uint64_t&nbsp;HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Timestamp.|
68|uint64_t&nbsp;HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>ID of the distributed call chain tracing task.|
69|void&nbsp;HiSysEventRecord::GetParamNames(std::vector&lt;std::string&gt;&amp;&nbsp;params)|Obtains all key names of a system event.<br>Input arguments:<br>- **params**: key name array reference.<br>Return value:<br>None.|
70|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;int64_t&amp;&nbsp;value)|Parses the value of the **param** key in a system event into an int64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
71|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;uint64_t&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a uint64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
72|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;double&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a double value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
73|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::string&amp; value)|Parses the value of the **param** key in a system event into a string value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
74|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;int64_t&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into an int64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
75|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;uint64_t&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a uint64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
76|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;double&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a double array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
77|int&nbsp;HiSysEventRecord::GetParamValue(const std::string&amp;&nbsp;param,&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;value)|Parses the value of the **param** key in a system event into a string array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
78
79#### C APIs
80
81HiSysEvent listening is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
82
83> **NOTE**
84>
85> For details about the **HiSysEventRecord** argument in the **OnEvent** callback of **HiSysEventWatcher**, see Table 11 and Table 12 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
86
87  **Table 5** Description of C HiSysEventManager APIs
88
89| Name                                                    | Description                                                        |
90| ------------------------------------------------------------ | ------------------------------------------------------------ |
91| int OH_HiSysEvent_Add_Watcher(HiSysEventWatcher* watcher,<br>HiSysEventWatchRule rules[],<br>size_t ruleSize); | Adds a listener to listen for system events based on the specified rules.<br>Input arguments:<br>- **watcher**: watcher for system events.<br>- **rules**: array of event listening rules.<br>- **ruleSize**: length of the array of event listening rules.<br>Return value:<br>- **0**: The listener is added successfully.<br>- A negative value: The listener fails to be added.|
92| int OH_HiSysEvent_Remove_Watcher(HiSysEventWatcher* watcher); | Remove the watcher for system events.<br>Input arguments:<br>- **watcher**: watcher for system events.<br>Return value:<br>- **0**: The watcher is removed successfully.<br>- A negative value: The watcher fails to be removed. |
93
94
95  **Table 6** Description of the HiSysEventWatcher structure
96| Field     | Type                                  | Description                                                        |
97| ------------- | -------------------------------------------------- | ------------------------------------------------------------ |
98| OnEvent       | void (*)(HiSysEventRecord record);        | Callback object for system events.<br>Input arguments:<br>- **record**: real-time system event.<br>Return value:<br>None.|
99| OnServiceDied | void (*)();                                | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None. |
100
101  **Table 7** Description of the HiSysEventWatchRule structure
102| Field     | Type | Description                              |
103| ------------- | --------- | ---------------------------------- |
104| domain        | char[]    | Event domain.          |
105| name          | char[]    | Event name.          |
106| tag           | char[]    | Event tag.          |
107| ruleType      | int       | Event matching rule. For details about the values, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).      |
108| eventType     | int       | Event type. For details about the values, see Table 3 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md). The value **0** indicates all event types.      |
109
110### How to Develop
111
112#### C++ HiSysEvent Listening
113
1141. Import the corresponding header file.
115
116    ```c++
117    #include "hisysevent_manager.h"
118    ```
119
1202. Implement the callback API for the service domain.
121
122    ```c++
123    class TestListener : public OHOS::HiviewDFX::HiSysEventListener {
124    public:
125        void OnEvent(std::shared_ptr<HiSysEventRecord> record)
126        {
127            if (record == nullptr) {
128                return;
129            }
130            std::cout << record->AsJson() << std::endl;
131        }
132
133        void OnServiceDied()
134        {
135            std::cout << std::string("service disconnect, exit") << std::endl;
136            exit(0);
137        }
138    };
139    ```
140
1413. Call the listening API while passing in parameters such as **listener** and **rules**. When the service ends, disable event listening.
142
143    ```c++
144    auto testListener = std::make_shared<TestListener>();
145    // Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
146    ListenerRule tagRule("dfx");
147    // Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
148    ListenerRule regRule("dfx.*", RuleType::REGULAR);
149    // Add a ListenerRule object based on the event domain and event name, with RuleType set as PREFIX.
150    ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
151    std::vector<ListenerRule> sysRules;
152    sysRules.push_back(tagRule);
153    sysRules.push_back(regRule);
154    sysRules.push_back(domainNameRule);
155    // Start event listening.
156    auto ret = HiSysEventManager::AddListener(testListener, sysRules);
157    // Remove the listener when the service ends.
158    if (ret == 0) {
159       HiSysEventManager::RemoveListener(testListener);
160    }
161    ```
162
163#### C HiSysEvent Listening
164
1651. Import the corresponding header file.
166
167    ```c++
168    #include "hisysevent_manager_c.h"
169    ```
170
1712. Implement the callback API for the service domain.
172
173    ```c++
174    void OnEventTest(HiSysEventRecord record)
175    {
176        printf("OnEventTest: event=%s", record.jsonStr);
177    }
178
179    void OnServiceDiedTest()
180    {
181        printf("OnServiceDied");
182    }
183    ```
184
1853. Call the listening API while passing in parameters such as **watcher** and **rules**. When the service ends, disable event listening.
186
187    ```c++
188    HiSysEventWatcher watcher;
189    watcher.OnEvent = OnEventTest;
190    watcher.OnServiceDied = OnServiceDiedTest;
191    // Add a HiSysEventWatchRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
192    constexpr char DFX_TAG[] = "dfx";
193    HiSysEventWatchRule tagRule;
194    (void)strcpy_s(tagRule.tag, strlen(DFX_TAG) + 1, DFX_TAG);
195    tagRule.ruleType = 1;
196    tagRule.eventType = 0;
197    // Add a HiSysEventWatchRule object based on the event tag, with RuleType set as REGULAR.
198    constexpr char DFX_PATTERN_TAG[] = "dfx.*";
199    HiSysEventWatchRule regRule;
200    (void)strcpy_s(regRule.tag, strlen(DFX_PATTERN_TAG) + 1, DFX_PATTERN_TAG);
201    regRule.ruleType = 3;
202    regRule.eventType = 0;
203    // Add a HiSysEventWatchRule object based on the event domain and event name, with RuleType set as PREFIX.
204    constexpr char DOMAIN[] = "HIVIEWDFX";
205    constexpr char NAME[] = "APP_USAGE";
206    HiSysEventWatchRule domainNameRule;
207    (void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
208    (void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
209    domainNameRule.ruleType = 2;
210    domainNameRule.eventType = 0;
211    // Start event listening.
212    HiSysEventWatchRule rules[] = {tagRule, regRule, domainNameRule};
213    int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
214    // Remove the watcher when the service ends.
215    if (ret == 0) {
216        ret = OH_HiSysEvent_Remove_Watcher(&watcher);
217    }
218    ```
219
220### Development Examples
221
222#### C++ HiSysEvent Listening
223
224Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
225
2261. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
227
228    ```c++
229    external_deps = [
230      "hisysevent:libhisysevent",
231      "hisysevent:libhisyseventmanager",
232    ]
233    ```
234
2352. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
236
237    ```c++
238    #include <iostream>
239
240    #include "hisysevent_manager.h"
241
242    using namespace OHOS::HiviewDFX;
243
244    class TestListener : public HiSysEventQueryCallback {
245    public:
246        void OnEvent(std::shared_ptr<HiSysEventRecord> record)
247        {
248            if (record == nullptr) {
249                return;
250            }
251            std::cout << record->AsJson() << std::endl;
252        }
253
254        void OnServiceDied()
255        {
256            std::cout << std::string("service disconnect, exit") << std::endl;
257            exit(0);
258        }
259    };
260
261    void TestEventListening()
262    {
263        auto testListener = std::make_shared<TestListener>();
264        ListenerRule domainNameRule("HIVIEWDFX", "PLUGIN_LOAD", RuleType::WHOLE_WORD);
265        std::vector<ListenerRule> sysRules;
266        sysRules.push_back(domainNameRule);
267        auto ret = HiSysEventManager::AddListener(testListener, sysRules);
268        if (ret == 0) {
269            HiSysEventManager::RemoveListener(testListener);
270        }
271    }
272    ```
273
274#### C HiSysEvent Listening
275
276Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
277
2781. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
279
280    ```c++
281    external_deps = [ "hisysevent:libhisyseventmanager" ]
282
283    // for strcpy_s
284    deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
285    ```
286
2872. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
288
289    ```c++
290    #include <securec.h>
291
292    #include "hisysevent_manager_c.h"
293
294    void OnEventTest(HiSysEventRecord record)
295    {
296        printf("OnEventTest: event=%s", record.jsonStr);
297    }
298
299    void OnServiceDiedTest()
300    {
301        printf("OnServiceDied");
302    }
303
304    void TestEventListening()
305    {
306        HiSysEventWatcher watcher;
307        watcher.OnEvent = OnEventTest;
308        watcher.OnServiceDied = OnServiceDiedTest;
309        constexpr char DOMAIN[] = "HIVIEWDFX";
310        constexpr char NAME[] = "PLUGIN_LOAD";
311        HiSysEventWatchRule domainNameRule;
312        (void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
313        (void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
314        domainNameRule.ruleType = 1;
315        domainNameRule.eventType = 0;
316        HiSysEventWatchRule rules[] = {domainNameRule};
317        int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
318        if (ret == 0) {
319           ret = OH_HiSysEvent_Remove_Watcher(&watcher);
320       }
321    }
322    ```
323