preface
At work we often print logs to view data and key logic. However, these logs can be extremely difficult to find when there are too many project logs and non-standard log printing makes the code look less neat and elegant, so I want to share a method of wrapping color-printed logs.
The console method
Probably the most common way to print a log in JS is console.log. But console gives us so many different types of printing methods. For details, see the introduction of Console (Portal) on MDN. I mainly use console.log(), console.trace(), console.error(), and console.warn(). For details, see the introduction of MDN. I won’t go into too much here.
Another thing you need is a booth character that requires the console attribute. A list is posted here. For details, see Portal.
code
So once we’ve done that we’re going to post the code right here.
@param {any} content hint content * @param {any} type Print type (log,trace,warn, Error) */ function colorLog(hint, content, type = "info") {const color = {info: "# 52C41A ", warn: "#faad14", error: "#f5222d", trace: "#66ccff", }; const hintContent = `%c${hint}`; const hintStyle = ` vertical-align: middle; display: flex; height: 100%; The line - height: 1.5; background: ${color[type]}; color: white; border-radius: 3px 0 0 3px; font-size: 14px; padding: 0 5px; box-sizing: border-box; background-clip: border-box; `; console[type](`${hintContent}`, `${hintStyle}`, content); } // call colorLog("test", "111", "info"); colorLog("test", "111", "error"); colorLog("test", "111", "warn"); colorLog("test", "111", "trace");Copy the code
Description:
- When log is used here, its invocation points to the encapsulated method and cannot be located to the place where the method is called. Therefore, I use the trace method to trace the invocation track.
- It is recommended to use pre-log when printing data and locating irrelevant calls. Trace is still needed when printing some key logic and tracing the call stack. Error and WARN can also track the call trajectory.
Display of print results
conclusion
The above is the color printing method of packaging. Hopefully, this will help you normalize your logs a little bit, and make your code a little bit cleaner.