Menguasai pengelogan peringkat fungsi ialah satu langkah penting ke arah memahami dan melaksanakan pengelogan komprehensif untuk keseluruhan sistem perisian. Dengan memfokuskan pada tahap fungsi berbutir, kami boleh membina asas kukuh yang menjadikan penskalaan kepada sistem yang kompleks menjadi mudah.
Berikut ialah lima perkara penting yang perlu diingat semasa menulis log untuk fungsi:
Nyatakan Asal Log:
Tulis dengan Menyahpepijat dalam Fikiran:
Kisah Kisah:
Uji Log Dengan Teliti:
Elakkan Pembalakan Berlebihan:
Elemen penting dalam rentetan log: Kemasukan Timestamp, ApplicationName, FileName, FunctionNamePERINGKAT, dan sebarang butiran lain yang berkaitan boleh meningkatkan keberkesanan log untuk aplikasi dengan ketara. Elemen ini menyediakan konteks penting dan memudahkan untuk mengesan aliran peristiwa, terutamanya apabila menyahpepijat atau memantau aplikasi. Ingat, matlamatnya adalah untuk mencipta log yang bermaklumat dan berguna, sambil menghormati privasi dan pertimbangan keselamatan.
Mesej harus menyampaikan: tindakan yang dimaksudkan, pemula tindakan dan input dan output.
Pertimbangkan entri log tidak berstruktur berikut:
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
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}
Contoh Kod dan Amalan Terbaik
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}
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!
Atas ialah kandungan terperinci Pembalakan Berkesan untuk Fungsi. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!