1# Logging Guide 2 3## Introduction 4In OpenHarmony, HiLog is used to export logs to the log services. Logs record user operations and system running statuses. Logs are an important part of a system, and quality logs are a must for system development. 5 6Logging has a significant negative impact on system performance. Therefore, it is necessary to make logging reasonably simple. Do not log unnecessary information to overwhelm developers. 7 8## Log Level 9 10- **[Rule] Use the appropriate log level based on actual conditions.** 11 12**Note:** The log level must match the log content. The following log levels are available: 13 14FATAL: indicates that a program or functionality is about to crash and the fault cannot be rectified. 15 16ERROR: indicates a program or functional error that affects the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data. 17 18WARN: indicates a severe, unexpected fault that has little impact on users and can be rectified by the programs themselves or through simple operations. 19 20INFO: used to record key service process nodes and exceptions (for example, no network signal or login failure) that occur during service running. These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions. 21 22DEBUG: used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults. DEBUG logs are not recorded in official versions by default. They are available in debug versions or in official versions with the debug function enabled. 23 24## Log Content 25 26- **[Rule] Describe the log content in fluent English (grammatically correct and clear description with no typos).** 27 28**Note:** The log content must be clear and concise so that developers can know what happened by reading the log, instead of analyzing the related code. A syntax- and semantics-compliant log also helps the log analysis tool automatically parse the log. Example: 29 30A log recording "1234" is meaningless to anyone except the coder themselves. 31 32A log recording "Error happened" does not indicate where the error occurred or the cause of the error. Such a log is not helpful for fault locating. 33 34- **[Rule] Do not log privacy information.** 35 36**Note:** Privacy information, such as hardware serial numbers, personal accounts, passwords, and identities, should not be logged. The scope of the privacy information complies with national and regional policies. 37 38- **[Rule] Do not log service-irrelevant information.** 39 40**Note:** Do not log any information irrelevant to the service code, such as the issue number, requirement number, department name, developer name, employee ID, name abbreviation, weather, and mood. 41 42- **[Rule] Do not log repeated information.** 43 44**Note:** Do not print logs with the same content in different places. It would hinder developers in locating the code during fault locating. 45 46- **[Rule] Do not call service interface functions in logs.** 47 48**Note:** Logging should not affect the normal service process. Generally, the impact of log code on the service logic is ignored during fault locating or code walk-through. 49 50- **[Rule] Do not commit logs used during development and debugging to the code repository.** 51 52**Note:** To speed up fault locating, you may print a line of logs for each step in the code or print various variables (which may include privacy information). 53You must delete these code lines before committing the final code to the code repository. 54 55- **[Recommendation] Display the log content in one line.** 56 57**Note:** A line usually contains about 100 characters. Try your best not to include more than 160 characters in a log. 58 59## When to Print 60 61- **[Rule] Do not print logs in the normal process of high-frequency code.** 62 63**Note:** Do not print logs for frequently called interface functions in big data processing, high-frequency software and hardware interrupt processing, protocol data stream processing, multimedia audio and video stream processing, display screen refresh processing, and other scenarios where the code keeps running as long as the system does not sleep. However, you can print logs in their error branches. Logs added during development and debugging must be cleared or disabled when code is committed to the code repository. 64 65- **[Rule] Restrict the logging frequency for logs that may be recorded repeatedly.** 66 67**Note:** If it is proved that some log records may occur multiple times, you are advised to restrict the logging frequency to avoid a large number of log copies with identical (or very similar) information. 68 69- **[Rule] Print logs for events that are unlikely to happen.** 70 71**Note:** According to Murphy's Law, anything that can go wrong will go wrong. Always print logs for points that are unlikely to happen. 72 73- **[Recommendation] Generate log strings during logging.** 74 75**Note:** Log strings should be generated as late as possible, best at the time when the log is printed. In this way, the strings will not be generated when the log function is disabled, therefore minimizing the system overhead. 76 77## Log Format 78 79 80- **[Rule] Log events in the who-does-what format.** 81 82- **[Rule] Log status changes in the format of state\_name:s1->s2, reason:msg.** 83 84- **[Rule] Log parameter values in the format of name1=value1, name2=value2...**. 85 86- **[Rule] Log successful code execution using the statement "xxx successful".** 87 88- **[Rule] Log code execution failures using the statement "xxx failed. Please xxx." Include possible solutions in the logs.** 89 90 Example: "Connection to the server failed. Please check network configuration." 91 92## Guide for Printing Common Logs 93 94### Process Logs 95 96 97- **[Recommendation] Log key service process nodes, including the service start point, key condition branch, error processing point, and service end point.** 98 99### Database Logs 100 101- **[Recommendation] Log database operations and related information.** 102 103**Note:** Common database operations include 104Create, Read, Update, Delete (CRUD). The initiator, type, and result (successful or failed) of each operation should be logged. However, the detailed content of the operation and operation result should not be logged to prevent user privacy leakage. The number of returned results can be logged. 105 106- **[Recommendation] Record the operation duration in database operation logs for performance-sensitive services.** 107 108**Note:** For performance-sensitive services, database operations (including reading and writing data) are key performance nodes, and the operation duration should be logged and used as a reference for performance profiling. 109 110- **[Recommendation] Log database job information.** 111 112**Note:** Log the job name, execution content, start time, end time, and execution result. 113 114### File Logs 115- **[Recommendation] Log operations on files and related information.** 116 117**Note:** Common file operations include creating, opening, reading, writing, closing, and deleting files as well as obtaining file attributes. The initiator, type, and result of each operation should be logged. However, the file content should not be logged to prevent user privacy leakage or system vulnerability exposure. The system file name and file handle value can be logged, but the user file name should not. 118 119- **[Recommendation] Print only one log for batch file operations.** 120 121**Note:** For example, if files are deleted in batches, do not record a log for each file deletion. Instead, log the number of deleted files. If the directory where a deleted file is located is created by the system, log the directory name as well. 122 123### Key Object/Object Pool Logs 124 125**Note:** A key object/object pool may be a class or struct, a queue or stack data structure, or a simple variable of the primitive data type. It plays a key role in the system and is used for system scheduling control, status recording, and information transfer. 126 127- **[Recommendation] Log the operations, results, and status changes of key objects.** 128 129**Note:** Object operations include creating, loading, unloading, and releasing objects. For key object operations, log the operation subject, type, and result. For status operations, log the values before and after the status change. 130 131### Thread Logs 132 133- **[Recommendation] Log thread operations and related information.** 134 135**Note:** Thread operations include creating, starting, pausing, and terminating threads. Record the operation type, operation result, thread number, and thread name in the log. (A thread name must be set for important threads.) 136 137- **[Recommendation] Logs must be recorded when a thread enters an infinite loop or deadlock.** 138 139**Note:** A mechanism must be provided for detecting deadlocks or infinite loops that occur in threads with logic such as lock waiting, asynchronous processing, and cyclic processing, and logs must be recorded when an error occurs. 140 141- **[Recommendation] Log message processing information for message processing threads.** 142 143**Note:** Log the information such as the message name, processing result, and processing duration. For high-frequency messages, you can record logs only when an error occurs during message processing. 144 145### Concurrency Control Logs 146 147**Note:** Concurrency control objects may be locks, critical sections, and semaphores. 148 149- **[Recommendation] Log operations on concurrency control objects and related information.** 150 151**Note:** Concurrency control operations include creating, occupying, releasing, and waiting. Log information such as the operation type, operation object name, operation result, and operation location. 152 153### Shared Memory Logs 154 155**Note:** Shared memory is a common inter-process communication method in software systems. It is used to share or transfer data between modules. The data stored in the shared memory may be configuration data, database data, and the like. 156 157- **[Recommendation] Log operations on the shared memory and related information.** 158 159**Note:** The operations on the shared memory include creating, deleting, setting, querying, and destroying data. Log the operator, operation type, and operation result. 160 161### Interface Interaction Logs 162 163 164There are internal and external system interfaces. Internal interfaces refer to the interfaces between subsystems and modules within the system. These interfaces include inter-module message sending interfaces, IPC interfaces, and RPC interfaces. 165 166- **[Recommendation] Record interface interaction information.** 167 168**Note:** Interface interaction information includes the interface caller, message content, processing result, and return value. User privacy information must be excluded from the message content and return value. 169 170### State Machine Logs 171 172- **[Recommendation] Log state machine operations and state change information.** 173 174**Note:** The operations on a state machine include creating, starting, ending, and destroying the state machine as well as changing its state. The state machine is usually driven by external conditions (such as messages and resources). State change information must be logged, such as the state names before and after the state change and the external conditions that cause the change. 175 176### Other OS Resources 177The other OS resources refer to resources that are not mentioned in the preceding sections, such as sockets and timers. OS resources such as files and threads are mentioned before and are not covered in this part. 178 179- **[Recommendation] Log the process and result of socket connection establishment, connection maintenance, disconnection, and causes.** 180 181- **[Recommendation] Log the timer startup, reset, destruction, and timeout processes.** 182 183- **[Recommendation] Comply with the preceding logging principles when using other similar OS resources.** 184 185## HiLog API Usage Specifications 186 187 188- **[Rule] Each service domain must have an independent domain ID.** 189 190**Note:** Before using the HiLog API to print logs, every service domain must apply for a domain ID from the DFX. The domain ID is used to measure and control the quality of a single service log. You can use the domain ID to filter out your own service logs for analysis. Do not use domain IDs of others. For test code, use the domain ID 0xD000F00. 191 192Range of the domain IDs: **0xD000001\-0xD0FFFFF** 193 194- **[Recommendation] Use the domain ID allocated to your domain based on a certain layer and module granularity.** 195 196**Note:** A domain ID is a 32-bit integer expressed in 16-bit format. The domain ID is the format of 0xD0xxxyy, where D0 is the domain ID, the most significant 12 bits of ***xxx*** are the value allocated by the DFX, and the least significant 8 bits of ***yy*** are for internal use in the service domain. Domain IDs allocated among your service domain must be able to locate your internal organizations or modules and reflect their log quality. The DFX conducts logging control based on the domain IDs to prevent the logging of a single module from affecting other modules in the same service domain. For example, the BT service domain is further divided as follows by module: 197 198 199 APP | BT-App1 BT-App2 200 --------------------------------------- 201 Framework | BT-Service1 BT-Service2 202 --------------------------------------- 203 HAL | BT-HAL 204 --------------------------------------- 205 Kernel | BT-Driver1 BT-Driver2 206 207Therefore, domain IDs allocated to BT can be further divided as follows: 208| Domain Name| Domain ID | 209|----|----| 210| BT | 0xD000100 | 211| BT-App1 | 0xD000101 | 212| BT-App2 | 0xD000102 | 213| BT-Service1 | 0xD000103 | 214| BT-Service2 | 0xD000104 | 215| BT-HAL | 0xD000105 | 216| BT-Driver1 | 0xD000106 | 217| BT-Driver2 | 0xD000107 | 218 219- **[Rule] The log service controls the log traffic of each service. Changing the default traffic threshold must be approved by the DFX.** 220 221**Note:** The default log traffic threshold of each domain ID is **10240 Bytes/s** . Any change to the default threshold must be approved by the DFX. 222 223- **[Rule] Correctly set the log formatting privacy tags {public} and {private}**. 224 225**Note:** Privacy parameter IDs {public} and {private} indicate whether the log content of each parameter contains sensitive privacy information. The HiLog API automatically outputs the content of the {public} parameter in plaintext and filters the content of the {private} parameter using <private>. Set privacy parameter IDs only after you analyze the log content. Example: 226 227Source code: 228 229 230 HiLog.info(LABEL, "Device Name:%{public}s, IP:%{private}s.", DeviceName, ip); 231 232 233Log output: 234 235 236 11-11 09:19:00.932 1513 1513 E 00500/Settings: MyPad001, IP:<private> 237