1# Using hiTraceChain (C/C++)
2
3## Overview
4
5hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing on the device side. It allows the calls made in a service process to be traced, helping locating issues across threads, processes, and devices. With hiTraceChain, a unique ID is generated for a service process, passed throughout the service process, and associated with various output information (including application events, system time, and logs). During debugging and fault locating, you can use this unique ID to quickly correlate various information related to the service process. hiTraceChain provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a service process and locate faults across devices, processes, and threads.
6
7## Available APIs
8
9The APIs for distributed call chain tracing are provided by the **hiTraceChain** module. For details, see [Hitrace](../reference/apis-performance-analysis-kit/_hitrace.md).
10
11| API| Description|
12| -------- | -------- |
13| HiTraceId OH_HiTrace_BeginChain(const char *name, int flags) | Starts call chain tracing.|
14| void OH_HiTrace_EndChain() | Stops call chain tracing.|
15| HiTraceId OH_HiTrace_GetId() | Obtains the trace ID in TLS of this thread. |
16| void OH_HiTrace_SetId(const HiTraceId *id) | Sets the trace ID of this thread.|
17| void OH_HiTrace_ClearId(void) | Clears the trace ID of this thread and invalidates it.|
18| HiTraceId OH_HiTrace_CreateSpan(void) | Creates a span ID based on the trace ID of this thread.|
19| void OH_HiTrace_Tracepoint(HiTrace_Communication_Mode mode, HiTrace_Tracepoint_Type type, const HiTraceId *id, const char *fmt, ...) | Prints HiTrace information, including the trace ID.|
20| void OH_HiTrace_InitId(HiTraceId *id) | Initializes a **HiTraceId** instance.|
21| void OH_HiTrace_IdFromBytes(HiTraceId *id, const uint8_t *pIdArray, int len) | Creates a **HiTraceId** instance based on a byte array.|
22| bool OH_HiTrace_IsIdValid(const HiTraceId *id) | Checks whether a trace ID is valid.|
23| bool OH_HiTrace_IsFlagEnabled(const HiTraceId *id, HiTrace_Flag flag) | Checks whether the specified trace flag is enabled in a **HiTraceId** instance .|
24| void OH_HiTrace_EnableFlag(const HiTraceId *id, HiTrace_Flag flag) | Enables the specified trace flag in a **HiTraceId** instance.|
25| int OH_HiTrace_GetFlags(const HiTraceId *id) | Obtains the trace flags in a **HiTraceId** instance.|
26| void OH_HiTrace_SetFlags(HiTraceId *id, int flags) | Sets trace flags in a **HiTraceId** instance.|
27| uint64_t OH_HiTrace_GetChainId(const HiTraceId *id) | Obtains a trace chain ID.|
28| void OH_HiTrace_SetChainId(HiTraceId *id, uint64_t chainId) | Sets the trace chain ID in a **HiTraceId** instance.|
29| uint64_t OH_HiTrace_GetSpanId(const HiTraceId *id) | Obtains the span ID in a **HiTraceId** instance.|
30| void OH_HiTrace_SetSpanId(HiTraceId *id, uint64_t spanId) | Sets the span ID in a **HiTraceId** instance.|
31| uint64_t OH_HiTrace_GetParentSpanId(const HiTraceId *id) | Obtains the parent span ID in a **HiTraceId** instance.|
32| void OH_HiTrace_SetParentSpanId(HiTraceId *id, uint64_t parentSpanId) | Sets the parent span ID in a **HiTraceId** instance.|
33| int OH_HiTrace_IdToBytes(const HiTraceId* id, uint8_t* pIdArray, int len) | Converts a **HiTraceId** instance into a byte array for caching or transfer.|
34
35
36## Example
37
381. Create a native C++ application in DevEco Studio. The project created by default contains the **index.ets** file, and a **hello.cpp** or **napi_init.cpp** file is generated in the **entry\src\main\cpp** directory. In this example, the generated file is **hello.cpp**.
39    The code of **index.ets** is as follows. The function **testNapi.add()** defined in **hello.cpp** is called in **onClick()**.
40    ```
41    import hilog from '@ohos.hilog';
42    import testNapi from 'libentry.so'
43
44    @Entry
45    @Component
46    struct Index {
47        @State message: string = 'Hello World'
48
49        build() {
50            Row() {
51            Column() {
52                Text(this.message)
53                .fontSize(50)
54                .fontWeight(FontWeight.Bold)
55                .onClick(() => {
56                    hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3));
57                })
58            }
59            .width('100%')
60            }
61            .height('100%')
62        }
63    }
64
652. Add the link of **libhitrace_ndk.z.so** to **CMakeLists.txt**.
66
67    ```
68   // CMakeLists.txt
69   # Minimum version of CMake.
70   cmake_minimum_required(VERSION 3.4.1)
71   project(MyApplication)
72
73   set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
74
75   include_directories(${NATIVERENDER_ROOT_PATH}
76                       ${NATIVERENDER_ROOT_PATH}/include)
77   add_library(entry SHARED hello.cpp)
78   target_link_libraries(entry PUBLIC libace_napi.z.so libhitrace_ndk.z.so)
79   ```
80
813. Include the hiTrace header file in the **hello.cpp** file.
82
83    ```c++
84    #include "hitrace/trace.h"
85    ```
86
874. In **Add()** of **hello.cpp**, use **OH_HiTrace_BeginChain()** to start a trace and use **OH_HiTrace_EndChain()** to stop the trace.
88
89    ```c++
90    #include "napi/native_api.h"
91    #include "hitrace/trace.h"
92    static napi_value Add(napi_env env, napi_callback_info info)
93    {
94        // Start distributed tracing.
95        OH_HiTrace_BeginChain("hitraceTest", HITRACE_FLAG_DEFAULT);
96        // Stop distributed tracing. (This is for reference only. Set the start and stop points to match your case.)
97        OH_HiTrace_EndChain();
98        size_t requireArgc = 2;
99        size_t argc = 2;
100        napi_value args[2] = {nullptr};
101
102        napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
103
104        napi_valuetype valuetype0;
105        napi_typeof(env, args[0], &valuetype0);
106
107        napi_valuetype valuetype1;
108        napi_typeof(env, args[1], &valuetype1);
109
110        double value0;
111        napi_get_value_double(env, args[0], &value0);
112
113        double value1;
114        napi_get_value_double(env, args[1], &value1);
115
116        napi_value sum;
117        napi_create_double(env, value0 + value1, &sum);
118
119        return sum;
120
121    }
122    ```
123
1245. Run the project, and an HAP application is generated on the device. Click "Hello World". The **Add()** function in **hello.cpp** will be called. View the trace log, which is as follows:
125    ```text
126    11-02 15:13:28.922  21519-21519  C02D03/HiTraceC                  com.example.hitracechaintest     I  [a92ab94c18e1341 0 0][dict]HiTraceBegin name:hitraceTest event flags:0x01.
127    11-02 15:13:28.930  21519-21519  C02D03/HiTraceC                  com.example.hitracechaintest     I  [a92ab94c18e1341 324c3a3 0][dict]HiTraceEnd.
128   ```
129