• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# HiSysEvent Query
2
3
4## Overview
5
6HiSysEvent allows you to query system events by specifying search criteria. For example, for a power consumption module, you can query required system events for analysis.
7
8
9## How to Develop
10
11### Available APIs
12
13#### C++ Event Query API
14
15HiSysEvent query is implemented using the API provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
16
17> **NOTE**
18>
19> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
20
21  **Table 1** Description of the HiSysEvent query API
22
23| API| Description|
24| -------- | -------- |
25| int32_t Query(struct&nbsp;QueryArg&amp;&nbsp;arg,<br>std::vector&lt;QueryRule&gt;&amp;&nbsp;rules,<br>std::shared_ptr&lt;HiSysEventQueryCallback&gt;&nbsp;callback) | Queries system events by search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
26
27  **Table 2** Description of QueryArg objects
28
29| Attribute| Type| Description|
30| -------- | -------- | -------- |
31| beginTime | long long | Start time for query. The value is a Unix timestamp, in milliseconds.|
32| endTime | long long | End time for query. The value is a Unix timestamp, in milliseconds.|
33| maxEvents | int | Maximum number of returned events.|
34
35  **Table 3** Description of QueryRule objects
36
37| API| Description|
38| -------- | -------- |
39| QueryRule(const&nbsp;std::string&amp;&nbsp;domain,<br>const&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>**eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
40
41  **Table 4** Description of HiSysEventQueryCallback objects
42
43| API| Description|
44| -------- | -------- |
45| void&nbsp;HiSysEventQueryCallback::OnQuery(std::shared_ptr&lt;std::vector&lt;HiSysEventRecord&gt;&gt;&nbsp;sysEvents) | Callback object for event query.<br>Input arguments:<br>- **sysEvents**: event list.|
46| void&nbsp;HiSysEventQueryCallback::OnComplete(int32_t&nbsp;reason,&nbsp;int32_t&nbsp;total) | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
47
48#### C Event Query API
49
50HiSysEvent query 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/).
51
52 **Table 5** Description of the HiSysEvent query API
53
54| API                                                    | Description                                                        |
55| ------------------------------------------------------------ | ------------------------------------------------------------ |
56| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **ruleSize**: number of event filtering rules.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
57
58 **Table 6** Description of the HiSysEventQueryArg structure
59
60| Attribute | Type| Description                                                |
61| --------- | -------- | ---------------------------------------------------- |
62| beginTime | int64_t  | Start time for query. The value is a Unix timestamp, in milliseconds.|
63| endTime   | int64_t  | End time for query. The value is a Unix timestamp, in milliseconds.|
64| maxEvents | int32_t  | Maximum number of returned events.                    |
65
66**Table 7** Description of the HiSysEventQueryRule structure
67
68| Attribute     | Type | Description                              |
69| ------------- | --------- | ---------------------------------- |
70| domain        | char[]    | Event domain.          |
71| eventList     | char\[][] | Event name list.      |
72| eventListSize | size_t    | Size of the event name list.  |
73| condition     | char*     | Custom event parameter conditions for the query.|
74
75The **condition** parameter must be in the specified JSON string format. For example:
76
77```json
78{
79    "version":"V1",
80    "condition":{
81        "and":[
82            {"param":"type_","op":">","value":0},
83            {"param":"uid_","op":"=","value":1201}
84        ],
85        "or":[
86            {"param":"NAME","op":"=","value":"SysEventService"},
87            {"param":"NAME","op":"=","value":"SysEventSource"}
88        ]
89    }
90}
91```
92
93- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
94- The **condition** field is mandatory, indicating the input condition.
95  - The **and** field is optional, indicating the AND relationship between conditions.
96  - The **or** field is optional, indicating the OR relationship between conditions.
97    - The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
98    - The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
99    - The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
100
101**Table 8** Description of the HiSysEventQueryCallback structure
102
103| Attribute  | Type                                          | Description                                                        |
104| ---------- | -------------------------------------------------- | ------------------------------------------------------------ |
105| OnQuery    | void (*)(HiSysEventRecord records[], size_t size); | Callback object for event query.<br>Input arguments:<br>- **records**: event list.<br>- **size**: size of the event list.|
106| OnComplete | void (*)(int32_t reason, int32_t total);           | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
107
108**Table 9** Description of the HiSysEventRecord event structure
109
110| Attribute | Type           | Description                      |
111| --------- | ------------------- | -------------------------- |
112| domain    | char[]              | Event domain.          |
113| eventName | char\[]             | Event name.              |
114| type      | HiSysEventEventType | Event type.              |
115| time      | uint64_t            | Event timestamp.            |
116| tz        | char\[]             | Event time zone.              |
117| pid       | int64_t             | Process ID of the event.            |
118| tid       | int64_t             | Thread ID of the event.            |
119| uid       | int64_t             | User ID of the event.            |
120| traceId   | uint64_t            | Distributed call chain trace ID of the event.    |
121| spandId   | uint64_t            | Span ID for the distributed call chain trace of the event.  |
122| pspanId   | uint64_t            | Parent span ID for the distributed call chain trace of the event.|
123| traceFlag | int                 | Distributed call chain trace flag of the event.  |
124| level     | char*               | Event level.              |
125| tag       | char*               | Event tag.              |
126| jsonStr   | char*               | Event content.              |
127
128**Table 10** Description of HiSysEventRecord APIs
129
130| API                                                    |                                                              |
131| ------------------------------------------------------------ | ------------------------------------------------------------ |
132| void OH_HiSysEvent_GetParamNames(const HiSysEventRecord& record, char*** params, size_t& len); | Obtains all parameter names of an event.<br>Input arguments:<br>- **record**: event structure.<br>- **params**: parameter name array.<br>- **len**: size of the parameter name array.|
133| int OH_HiSysEvent_GetParamInt64Value(const HiSysEventRecord& record, const char* name, int64_t& value); | Parses the parameter value in the event to an int64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the int64_t type.|
134| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to an uint64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the uint64_t type.|
135| int OH_HiSysEvent_GetParamDoubleValue(const HiSysEventRecord& record, const char* name, double& value); | Parses the parameter value in the event to a double value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the double type.|
136| int OH_HiSysEvent_GetParamStringValue(const HiSysEventRecord& record, const char* name, char** value); | Parses the parameter value in the event to a char array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: char\* reference.|
137| int OH_HiSysEvent_GetParamInt64Values(const HiSysEventRecord& record, const char* name, int64_t** value, size_t& len); | Parses the parameter value in the event to a int64_t array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: int64_t\* reference.<br>- **len**: array size.|
138| int OH_HiSysEvent_GetParamUint64Values(const HiSysEventRecord& record, const char* name, uint64_t** value, size_t& len); | Parses the parameter value in the event to a uint64_t array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: uint64_t\* reference.<br>- **len**: array size.|
139| int OH_HiSysEvent_GetParamDoubleValues(const HiSysEventRecord& record, const char* name, double** value, size_t& len); | Parses the parameter value in the event to a double array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: double\* reference.<br>- **len**: array size.|
140| int OH_HiSysEvent_GetParamStringValues(const HiSysEventRecord& record, const char* name, char*** value, size_t& len); | Parses the parameter value in the event to a char* array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: char\*\* reference.<br>- **len**: array size.|
141
142The return values of the HiSysEventRecord APIs are described as follows:
143
144- **0**: The parsing is successful.
145- -**1**: The event fails to be initialized.
146- -**2**: The parameter name does not exist.
147- -**3**: The type of the parameter value to be parsed does not match the type of the input parameter value.
148
149### How to Develop
150
151#### C++ HiSysEvent Query API
152
1531. Import the corresponding header file:
154
155   ```c++
156   #include "hisysevent_manager.h"
157   ```
158
1592. Implement the callback API.
160
161   ```c++
162   class TestQueryCallback : public HiSysEventQueryCallback {
163   public:
164       void OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) override
165       {
166           if (sysEvents == nullptr) {
167           	return;
168           }
169           for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
170               std::cout << event.AsJson() << std::endl;
171           });
172       }
173
174       void OnComplete(int32_t reason, int32_t total) override
175       {
176           std::cout << "Query completed" << std::endl;
177           return;
178       }
179   };
180   ```
181
1823. Call the query API while passing in the query parameter, rule, and callback object.
183
184   ```c++
185   // Create a query parameter object.
186   long long startTime = 0;
187   long long endTime = 1668245644000; //2022-11-12 09:34:04
188   int queryCount = 10;
189   QueryArg arg(startTime, endTime, queryCount);
190
191   // Create a query rule object.
192   QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
193   std::vector<QueryRule> queryRules = { rule };
194
195   // Create a query callback object.
196   auto queryCallback = std::make_shared<TestQueryCallback>();
197
198   // Call the query API.
199   HiSysEventManager::Query(arg, queryRules, queryCallback);
200   ```
201
202#### C HiSysEvent Query API
203
2041. Import the corresponding header file:
205
206   ```c++
207   #include "hisysevent_manager_c.h"
208   ```
209
2102. Implement the callback API.
211
212   ```c++
213   void OnQueryTest(HiSysEventRecord records[], size_t size)
214   {
215       for (size_t i = 0; i < size; i++) {
216           printf("OnQuery: event=%s", records[i].jsonStr);
217       }
218   }
219
220   void OnCompleteTest(int32_t reason, int32_t total)
221   {
222       printf("OnCompleted, res=%d, total=%d\n", reason, total);
223   }
224   ```
225
2263. Call the query API while passing in the query parameter, rule, and callback object.
227
228   ```c++
229   // Create a query parameter object.
230   HiSysEventQueryArg arg;
231   arg.beginTime = 0;
232   arg.endTime = 1668245644000; //2022-11-12 09:34:04
233   arg.maxEvents = 10;
234
235   // Create a query rule object.
236   constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
237   constexpr char TEST_NAME[] = "PLUGIN_LOAD";
238   HiSysEventQueryRule rule;
239   (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
240   (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
241   rule.eventListSize = 1;
242   rule.condition = nullptr;
243   HiSysEventQueryRule rules[] = { rule };
244
245   // Create a query callback object.
246   HiSysEventQueryCallback callback;
247   callback.OnQuery = OnQueryTest;
248   callback.OnComplete = OnCompleteTest;
249
250   // Call the query API.
251   OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
252   ```
253
254### Development Example
255
256#### C++ HiSysEvent Query
257
258Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
259
2601. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent_native** component to **BUILD.gn** of the service module.
261
262   ```c++
263   external_deps = [
264     "hisysevent_native:libhisysevent",
265     "hisysevent_native:libhisyseventmanager",
266   ]
267   ```
268
2692. Call the query API in the **TestQuery()** function of the service module.
270
271   ```c++
272   #include "hisysevent_manager.h"
273   #include <iostream>
274   #include <unistd.h>
275
276   using namespace OHOS::HiviewDFX;
277
278   class TestQueryCallback : public HiSysEventQueryCallback {
279   public:
280       void OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) override
281       {
282           if (sysEvents == nullptr) {
283           	return;
284           }
285           for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
286               std::cout << event.AsJson() << std::endl;
287           });
288       }
289
290       void OnComplete(int32_t reason, int32_t total) override
291       {
292           std::cout << "Query completed" << std::endl;
293           return;
294       }
295   };
296
297   int64_t GetMilliseconds()
298   {
299       auto now = std::chrono::system_clock::now();
300       auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
301       return millisecs.count();
302   }
303
304   void TestQuery()
305   {
306       // Create a query parameter object.
307       long long startTime = 0;
308       long long endTime = GetMilliseconds();
309       int maxEvents = 100;
310       QueryArg arg(startTime, endTime, maxEvents);
311
312       // Create a query rule object.
313       QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
314       std::vector<QueryRule> queryRules = { rule };
315
316       // Create a query callback object.
317       auto queryCallback = std::make_shared<TestQueryCallback>();
318
319       // Call the query API.
320       int ret = HiSysEventManager::Query(arg, queryRules, queryCallback);
321   }
322   ```
323
324#### C HiSysEvent Query
325
326Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
327
3281. Add the **libhisyseventmanager** dependency of the **hisysevent_native** component to the **BUILD.gn** file of the service module.
329
330   ```c++
331   external_deps = [ "hisysevent_native:libhisyseventmanager" ]
332
333   // for strcpy_s
334   deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
335   ```
336
3372. Call the query API in the **TestQuery()** function of the service module.
338
339   ```c++
340   #include "hisysevent_manager_c.h"
341   #include <securec.h>
342   #include <time.h>
343
344   void OnQueryTest(HiSysEventRecord records[], size_t size)
345   {
346       for (size_t i = 0; i < size; i++) {
347           printf("OnQuery: event=%s", records[i].jsonStr);
348       }
349   }
350
351   void OnCompleteTest(int32_t reason, int32_t total)
352   {
353       printf("OnCompleted, res=%d, total=%d\n", reason, total);
354   }
355
356   int64_t GetMilliseconds()
357   {
358       return time(NULL);
359   }
360
361   void TestQuery()
362   {
363       // Create a query parameter object.
364       HiSysEventQueryArg arg;
365       arg.beginTime = 0;
366       arg.endTime = GetMilliseconds();
367       arg.maxEvents = 100;
368
369       // Create a query rule object.
370       constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
371       constexpr char TEST_NAME[] = "PLUGIN_LOAD";
372       HiSysEventQueryRule rule;
373       (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
374       (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
375       rule.eventListSize = 1;
376       rule.condition = nullptr;
377       HiSysEventQueryRule rules[] = { rule };
378
379       // Create a query callback object.
380       HiSysEventQueryCallback callback;
381       callback.OnQuery = OnQueryTest;
382       callback.OnComplete = OnCompleteTest;
383
384       // Call the query API.
385       int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
386   }
387   ```
388