掌握函數級日誌記錄是理解和實現整個軟體系統全面日誌記錄的關鍵步驟。透過專注於功能的粒度級別,我們可以建立堅實的基礎,使擴展到複雜的系統變得輕而易舉。
為函數寫日誌時要記住以下五個重點:
指定日誌的來源:
在撰寫時牢記調試:
說故事:
徹底測試日誌:
避免過度記錄:
日誌字串中的基本元素: 包含Timestamp、ApplicationName、FileName、FunctionNameLEVEL 以及任何其他相關詳細資訊都可以顯著提高應用程式日誌的有效性。這些元素提供了關鍵的上下文,並使追蹤事件流變得更加容易,尤其是在偵錯或監視應用程式時。請記住,我們的目標是創建資訊豐富且有用的日誌,同時尊重隱私和安全考慮。
訊息應傳達:預期的操作、操作的發起者、輸入和輸出。
考慮以下非結構化日誌條目:
2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: Fetching mailing list 14777 2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: User 3654 opted out 2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: User 1334563 plays 4 of spades in game 23425656透過將這些條目建構為 JSON,我們增強了可讀性和易於解析:
2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: Fetching mailing list {"listid":14777} 2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: User opted out {"userid":3654} 2019-06-20T17:21:00.002899+00:00 myApp [c.d.g.UserRequestClass]: [getUser]: DEBUG: User plays {'user':1334563, 'card':'4 of spade', 'game':23425656}透過堅持這些實踐,我們可以確保我們的日誌資訊豐富、易於閱讀並且對偵錯有價值。
程式碼範例和最佳實踐
import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class UserService { private static final Logger logger = LogManager.getLogger(UserService.class); private Database database; public UserService(Database database) { this.database = database; } public int getTotalLikesInLast30Days(String userId) { logger.info("Request received to get all total likes in last 30 days for: {userId: " + userId + "}"); long startTime = System.nanoTime(); try { logger.debug("Fetching user with id: {userId: " + userId + "}"); User user = database.getUserById(userId); if (user == null || user.isDeleted() || user.isDeactivated()) { logger.warn("User not found or deactivated: {userId: " + userId + "}"); return 0; } LocalDate thirtyDaysAgo = LocalDate.now().minus(30, ChronoUnit.DAYS); logger.debug("Fetching posts for user since: {userId: " + userId + ", since: " + thirtyDaysAgo + "}"); List<Post> posts = database.getPostsByUserSince(user, thirtyDaysAgo); int totalLikes = 0; for (Post post : posts) { totalLikes += post.getLikes().size(); } long endTime = System.nanoTime(); // compute the elapsed time in nanoseconds long duration = (endTime - startTime); logger.info("Execution time: {timeInNanoseconds: " + duration + "}"); logger.info("Returning total likes in last 30 days for: {userId: " + userId + ", totalLikes: " + totalLikes + "}"); return totalLikes; } catch (Exception e) { logger.error("An error occurred: {message: " + e.getMessage() + "}", e); return 0; } } }以下是成功案例中日誌的外觀:
2024-01-07 14:00:00,001 [INFO] UserService.java:10 [com.example.UserService] (getTotalLikesInLast30Days) : Request received to get all total likes in last 30 days for: {userId: 123} 2024-01-07 14:00:00,002 [DEBUG] UserService.java:12 [com.example.UserService] (getTotalLikesInLast30Days) : Fetching user with id: {userId: 123} 2024-01-07 14:00:00,010 [DEBUG] UserService.java:18 [com.example.UserService] (getTotalLikesInLast30Days) : Fetching posts for user since: {userId: 123, since: 2023-12-08} 2024-01-07 14:00:00,020 [INFO] UserService.java:26 [com.example.UserService] (getTotalLikesInLast30Days) : Execution time: {timeInNanoseconds: 19000000} 2024-01-07 14:00:00,021 [INFO] UserService.java:28 [com.example.UserService] (getTotalLikesInLast30Days) : Returning total likes in last 30 days for: {userId: 123, totalLikes: 999}下面是發生異常時的樣子,例如當 Post 表不存在時:
2024-01-07 14:00:00,001 [INFO] UserService.java:10 [com.example.UserService] (getTotalLikesInLast30Days) : Request received to get all total likes in last 30 days for: {userId: 123} 2024-01-07 14:00:00,002 [DEBUG] UserService.java:12 [com.example.UserService] (getTotalLikesInLast30Days) : Fetching user with id: {userId: 123} 2024-01-07 14:00:00,010 [DEBUG] UserService.java:18 [com.example.UserService] (getTotalLikesInLast30Days) : Fetching posts for user since: {userId: 123, since: 2023-12-08} 2024-01-07 14:00:00,015 [ERROR] UserService.java:18 [com.example.UserService] (getTotalLikesInLast30Days) : An error occurred: {message: "Post table does not exist"}
Packages like log4j, slf4j, and many others can be used for better management of logs in large software programs.
Focusing on creating effective logs for each function can significantly improve the overall quality of logs for the entire software. This approach ensures that each part of the software is well-documented and can facilitate easier debugging and maintenance. Remember, a well-logged function contributes to a well-logged application.
Thank you for reading this blog. _Sayonara!
以上是有效的函數日誌記錄的詳細內容。更多資訊請關注PHP中文網其他相關文章!