Meaningful Customized Colorful Log Messages for your terminal without needing any External Library
Motivation: When I saw other libraries like colors were just used for making some lines colorful in terminal. I came up with this solution where you do not need to install any third party library and easily define beautiful log just by putting this function wherever you want.
Just copy and paste this code in your typescript project
type LogType = "error" | "info" | "log" | "success" | "warning";
type CustomLogType = (type: LogType, message: string) => void;
// Check if ANSI escape codes are supported
const isWindowsCmd = process.platform === "win32" && !process.env.TERM;
export const customLog: CustomLogType = (type, message) => {
// ANSI color codes (only if supported)
const styles: Record<LogType, string> = isWindowsCmd
? { error: "", log: "", success: "", warning: "", info: "" } // No colors in Windows CMD
: {
error: "\x1b[1m\x1b[37m\x1b[41m", // Bold White text on Red background
log: "\x1b[1m\x1b[37m\x1b[47m", // Bold White text on White background
success: "\x1b[1m\x1b[37m\x1b[42m", // Bold White text on Green background
warning: "\x1b[1m\x1b[30m\x1b[43m", // Bold Black text on Yellow background
info: "\x1b[1m\x1b[37m\x1b[46m" // Bold Text with Aqua Blue background
};
const reset = isWindowsCmd ? "" : "\x1b[0m"; // Reset styles (only if supported)
const formattedMessage = `${styles[type]}${message}${reset}`;
switch (type) {
case "error":
console.error(formattedMessage);
break;
case "info":
console.info(formattedMessage);
break;
case "warning":
console.warn(formattedMessage);
break;
default:
console.log(formattedMessage);
}
};
import { customLog } from "path_to_file";
customLog("error", "This is a Sample Error Message");
customLog("info", "This is a Sample Info Message");
customLog("log", "This is a Sample Log Message");
customLog("success", "This is a Sample Success Message");
customLog("warning", "This is a Sample Warning Message");
- ✅ Mac (Terminal, iTerm, VS Code Terminal, etc.) → Works fine.
- ✅ Windows (PowerShell, Windows Terminal, VS Code Terminal) → Works fine.
⚠️ Windows (Command Prompt) → ANSI codes may not work correctly. Use PowerShell or install chalk for compatibility.
You can also give this repository a star to show more people and they can use this repository.
- Om Patel