UNPKG

js-log-lib

Version:

浏览器和 node 共用的 log 样式,行为控制工具,可以自定义输出样式,其核心原理是采用了 ANSI 指令以及 css 属性,更多用法可以参照 ANSI 的详细介绍

412 lines (325 loc) 12.8 kB
# js-log-lib ## Introduction Browser and node common log style, behavior control tool, you can customize the output style, the core principle is the use of ANSI directives and css properties, more usage can refer to the ANSI detailed introduction ## Debugging Instructions 1.pnpm build 2. pnpm dev (debugging source code in node) 3. pnpm dev:umd (debugging in the browser) 4. Import the library in esm, cjs, window environment 5. See dev folder for details ## Contribute 1. Fork the repository 2. Star repository 3. Commit code 4. Create a Pull Request ## Instructions ### Installation `npm install js-log-lib` or `yarn add js-log-lib` or `pnpm install js-log-lib` ### Importing #### ESM ```javascript import { JSLog } from "js-log-lib"; ``` #### CJS ```javascript const { JSLog } = require("js-log-lib"); ``` #### In the browser ```html <script src="./node_modules/js-log-lib/dist/umd/index.js"></script> <script> console.log(JSLog); </script> ``` ### Getting started It's a little different in the browser environment than in Node It is recommended that you read types.ts and static.ts files carefully before using them to help you understand and use them Static. Ts https://gitee.com/DieHunter/js-log-lib/blob/master/src/static.ts file for a static variables, most of the instructions on this Types. Ts https://gitee.com/DieHunter/js-log-lib/blob/master/src/types.ts is the core of JSLog type, some functions of configuration items can be found in this #### Create a JSLog instance ```javascript const logger = new JSLog(); ``` #### Global configuration items Refer to the IGlobalOpts type in types.ts Global configuration items can be passed the following properties ```typescript type IGlobalOpts = Partial<{ text: string; // Text to print reset: boolean; // Whether to reset styles at the end type: string; // console type split: boolean; // Split or not, in node you can do this in a console.log, like this: console.log("1","2","3") and console.log("123"), where the former has Spaces between the characters and a split of true means that the former is used, and the latter is used only as a merge in the browser environment color: IColor[] | IColor; // front (back) color or its array, convenient to pass multiple color arguments, but some consoles seem to be incompatible textStyle: ITextStyle[] | ITextStyle; // Text styles or styles array cursor: ICursor; // Cursor control move: IMoveParams; // Cursor movement parameters scroll: number; // scrollbar rows style: Partial<CSSStyleDeclaration>; // CSS style object, browser only } >. ``` #### Default configuration In index, defaultOpts is the default configuration that will be used when the developer doesn't set the option ```typescript const defaultOpts: IGlobalOpts = { reset: true, type: "log", split: true, }; ``` #### Basic usage ##### 1.Print the characters ```typescript const logger = new JSLog(); logger.log({ text: "Yu's programming journey" }); // A-Yu's programming journey ``` ##### 2. Add global configuration items to the current instance ```typescript // Global configuration can be added either by passing it to the constructor or by mixins const logger = new JSLog({ type: "error", color: "red" }); logger.log({ text: "I'm an error" }); logger.mixins({ type: "info", color: "green" }); logger.log({ text: "I'm a success tip" }); ``` ##### 3. Clear all styles and actions ```typescript const logger = new JSLog({ type: "error", color: "red" }); logger.log({ text: "a yu" }); logger.clear(); logger.log({ text: "a yu" }); ``` ##### 4. Checks if the passed argument is allowed ```typescript const logger = new JSLog(); // In node logger.checkOptions({ style: {} }); // style-related properties are not available in node ``` ##### 5. Style adjustments In Node environment ```typescript // Use color to control the front (back) color of the text and textStyle to control the shape of the text (bold, italic, etc.) (Different consoles have different styles, which may cause conflicts or invalidates) // The style adjustment is actually done using ANSI encoding, and the instruction set can be found in the ANSIParams variable in stant.ts, where color and textStyle represent the operations for const logger = new JSLog(); logger.log({ text: "hello world", color: "cyan", // Font cyan textStyle: "bold", // bold }); ``` In the browser environment ```typescript // The browser can also use color and textStyle to control textStyle, but the style attribute can support more styles, which can be set by referring to the CSSStyleDeclaration type. This can lead to style conflicts logger.log({ text: "hello world", style: { color: "lightblue", background: "#333", margin: "10px" }, }); ``` ##### 6. Cursor control commands ```typescript // cursor control is only available in Node environment. Similar to style adjustment, it is done using ANSI encoding to output the corresponding command to the console, also refer to the ANSIParams variable in statically const logger = new JSLog(); logger.log({ text: "i m here" }); logger.log({ text: "i m here" }); logger.log({ text: "i m here", cursor: "eraseDisplay" }); // Clear the screen ``` ##### 7. Cursor position offset ```typescript // Cursor movement is the same as the cursor command above, except the distance is passed in const logger = new JSLog(); logger.log( { move: { direct: "right", position: 5, }, text: "Programming journey ", // Print the following characters first }, { move: { direct: "left", position: 14, }, text: "Yu's ", // Inserts the previous character to the left } ); // Output: A-Yu's programming journey ``` ##### 8. Scroll bar controls ```typescript // Implement a sliding scrollbar effect with the TimerManager timer or setinterval to print the number of rows every 500ms import { TimerManager } from "utils-lib-js"; const logger = new JSLog(); const timerManager = new TimerManager(); let scroll = 0; const timer = timerManager.add(() => { if (scroll <= -5) return timerManager.delete(timer); scroll--; logger.log({ text: scroll.toString(), scroll }); }, 500); ``` #### Other uses ##### 1.Chained calls to log ```typescript const logger = new JSLog(); logger.log({ text: "hello" }).log({ text: "world" }); ``` ##### 2.Print multiple types of logs on the same line ```typescript const logger = new JSLog({ split: false }); logger.log( { text: "A yu ", color: "red" }, { text: "brightCyan", color: "brightCyan" }, { text: "tour ", color: "bgBrightMagenta" } ); ``` ##### 3. the instruction set for the property ```typescript // As mentioned above, options allow you to pass in a directive to control styles or behavior, and some properties allow you to pass in an instruction set to apply styles in bulk logger.log({ text: "hello world", color: ["red", "bgBrightGreen"], // Red font with a bright green background textStyle: ["bold", "italic", "strikethrough"], // bold, italic, strikethrough }); ``` ##### 4. Some ANSI shortcuts in JSLog If you know the ANSI encoding instructions, then the following function can put the icing on the cherry Don't worry if you don't know, I have listed the commonly used ANSI in the static file for reference 1. ANSI coded instruction splicing ```typescript // Style control via getANSI and ANSI encoding. Use console or JSLog to output getANSI transfer characters to set corresponding instructions const logger = new JSLog(); const { getANSI } = logger; console.log(getANSI(`35`), "hello world"); // Output a purple string logger.log({ text: getANSI(`34`) + "hello world", }); // Output a blue string ``` 2. Color Settings ```typescript // If you are not familiar with ANSI, JSLog provides a set of semantic configuration functions to style colors using the getColor function below const logger = new JSLog(); const { getANSI, getColor } = logger; logger.log({ text: getANSI(getColor("bgBlue")) + "hello world", }); // Output a string with a blue background ``` 3. Font styles ```typescript // We can use the getTextStyle function below to set the font style const logger = new JSLog(); const { getANSI, getTextStyle } = logger; logger.log({ text: getANSI(getTextStyle("bold")) + "hello world", }); // Print a string in bold ``` Cursor manipulation ```typescript // Do cursor-related things with getCursor const logger = new JSLog(); const { getANSI, getCursor } = logger; logger.log( { text: "----------------------------" }, { text: getANSI(getCursor("toLineStart"), false) + "hello world", } ); // Move to the beginning of the line and print a character ``` 5. Cursor movement ```typescript // Use moveTo to move the cursor const logger = new JSLog(); const { getANSI, moveTo } = logger; logger.log( { text: "hello" }, { text: getANSI(moveTo({ direct: "right", position: 5 }), false) + "world", } ); // Move the cursor to the right 5 times ``` 6. Scroll bar movement ```typescript // scrollTo move the scrollbar const logger = new JSLog(); const { getANSI, scrollTo } = logger; logger.log({ text: getANSI(scrollTo(-2), false) + "hello world", }); // Move the scroll bar up 2 rows ``` 7. Reset styles ```typescript // The styles can be reset by running the reset function, because jslog is configured with the reset parameter, so the styles will only be applied to a log queue, to cancel the reset, you can pass reset: false at instantiation, here I just use console.log to show the effect const logger = new JSLog(); const { getANSI, getColor, reset } = logger; console.log( getANSI(getColor("bgBrightGreen")), "i m bgBrightGreen", reset(), "i m reset" ); ``` ##### 5. Advanced use of ANSI color instructions The color attribute can be used to set the corresponding color attribute of the log character. However, due to the limited number of instructions for color, there are many other colors that cannot be expressed, so ANSI provides two ways to set the color parameter 1. The first is the form of 256 color pallets, also known as compatibility mode, which requires setting the second ANSI parameter mode to 5: ```typescript const ANSI = `\x1B[38;5;<color>m`; ``` It supports setting the numbers 0-255: 0-15 are the standard colors, which are the color variables we used earlier 16-231 has 216 colors, which are arranged according to the RGB cube rule of order six, providing a variety of color combinations 232-255 are grayscale colors.These colors represent different gray levels, from black to white. 232 represents the darkest gray and 255 represents the brightest gray. We can print all 256 levels with the following code: ```typescript const logger = new JSLog(); const { getANSI, getRGB, reset } = logger; let color = ``; for (let i = 0; i < 255; i++) { color += `${getANSI( getRGB({ color: i, mode: "compatibility", type: "background" }) } '; } console.log(color, reset()); ``` Another way to set colors is to use the True Color mode. In True Color mode, you can specify the exact color by specifying RGB (red, green, and blue) values, rather than relying on a predefined color index, just like the rgb method in css. This mode requires the second ANSI parameter mode to be set to 2: ```typescript const ANSI = `\x1B[38;2;<r>;<g>;<b>m`; ``` It supports 256^3 (16777216 colors) of the number, and in true color mode you can define the exact color by specifying the intensity value of each color channel ```typescript const logger = new JSLog(); logger.log( { text: "hello", color: { red: 255 } }, { text: "A Yu's ", color: { green: 255 }, }, { text: "Programming trip ", color: { blue: 255, type: "background" } } ); ``` ##### 6. Cursor axis movement The function of coordinate displacement can be realized by configuring the move parameter ```typescript // Below we implement an oblique output string import { TimerManager } from "utils-lib-js"; const logger = new JSLog(); const timer = new TimerManager(); // Create the timer const str = "hello world"; const position = { row: 0, // Row col: 0, // column }; logger.log({ cursor: "eraseDisplay" }); // Clear the screen timer.add(() => { const _str = str[position.col]; if (!_str) timer.clear(); position.col++; position.row++; move(_str); }, 100); const move = (str) => logger.log({ text: str, move: { direct: "custom", position, }, }); ```