掌握函数级日志记录是理解和实现整个软件系统全面日志记录的关键步骤。通过专注于功能的粒度级别,我们可以构建坚实的基础,使扩展到复杂的系统变得轻而易举。
为函数编写日志时要记住以下五个要点:
指定日志的来源:
在编写时牢记调试:
讲故事:
彻底测试日志:
避免过度记录:
日志字符串中的基本元素: 包含 Timestamp、ApplicationName、FileName、FunctionName 、LEVEL 以及任何其他相关详细信息可以显着提高应用程序日志的有效性。这些元素提供了关键的上下文,使跟踪事件流变得更加容易,特别是在调试或监视应用程序时。请记住,我们的目标是创建信息丰富且有用的日志,同时尊重隐私和安全考虑。
消息应传达:预期的操作、操作的发起者以及输入和输出。
考虑以下非结构化日志条目:
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中文网其他相关文章!