LoginSignup
54
45

[javascript] カラフルなconsole.log

Last updated at Posted at 2024-04-02

はじめに

普段、一面の白いconsole.logを見て、イライラしたり、重要な情報を一目で見つけるのが難しいと感じたことはありませんか?今日は、console.logをカラフルに変える方法を皆さんに共有します。

エクスポート関数を作る

messageUtil.ts
export const success = (msg: string) => {
  console.log("\x1b[32m%s \x1b[0m", `SUCCESS: ${msg}`);
};

export const error = (msg: string) => {
  console.log("\x1b[31m%s \x1b[0m", `ERROR: ${msg}`);
};

export const warning = (msg: string) => {
  console.log("\x1b[33m%s \x1b[0m", `WARNING: ${msg}`);
};

export const task = (msg: string) => {
  console.log("\x1b[35m%s \x1b[0m", `TASK: ${msg}`);
};

export const info = (msg: string) => {
  if (!msg) return;
  const lines = msg.split("\n").filter(Boolean);
  for (const line of lines) {
    console.log("\x1b[34m%s \x1b[0m", `INFO: ${line}`);
  }
};

いざ使おう!

main.ts
import "module-alias/register"
import * as MU from "@util/messageUtil"

MU.info("infoです");
MU.task("taskです");
MU.warning("warningです");
MU.error("errorです");

下記のようにカラフルなログができましたね!
image.png

カラー一覧
Color Name Code
Reset \x1b[0m
Bright \x1b[1m
Dim \x1b[2m
Underscore \x1b[4m
Blink \x1b[5m
Reverse \x1b[7m
Hidden \x1b[8m
FgBlack \x1b[30m
FgRed \x1b[31m
FgGreen \x1b[32m
FgYellow \x1b[33m
FgBlue \x1b[34m
FgMagenta \x1b[35m
FgCyan \x1b[36m
FgWhite \x1b[37m
FgGray \x1b[90m
BgBlack \x1b[40m
BgRed \x1b[41m
BgGreen \x1b[42m
BgYellow \x1b[43m
BgBlue \x1b[44m
BgMagenta \x1b[45m
BgCyan \x1b[46m
BgWhite \x1b[47m
BgGray \x1b[100m

全部出力してみました!
image.png

補足:タイムスタンプを追加する

dayjsライブラリを使用してログにタイムスタンプを追加することで、ログが記録された正確な時刻を把握することが可能になります。

image.png
実装は以下です。

messageUtil.ts
import dayjs from "dayjs";

const getTime = () => {
  return dayjs().format("HH:mm:ss:SSS");
};
const getLabel = () => {
  return `[${getTime()}]`;
};

export const success = (msg: string) => {
  console.log("\x1b[32m%s \x1b[0m", `${getLabel()} SUCCESS: ${msg}`);
};

export const error = (msg: string) => {
  console.log("\x1b[31m%s \x1b[0m", `${getLabel()} ERROR: ${msg}`);
};

export const warning = (msg: string) => {
  console.log("\x1b[33m%s \x1b[0m", `${getLabel()} WARNING: ${msg}`);
};

export const task = (msg: string) => {
  console.log("\x1b[35m%s \x1b[0m", `${getLabel()} TASK: ${msg}`);
};

export const info = (msg: string) => {
  if (!msg) return;
  const lines = msg.split("\n").filter(Boolean);
  for (const line of lines) {
    console.log("\x1b[34m%s \x1b[0m", `${getLabel()} INFO: ${line}`);
  }
};

補足:呼び出し位置を表示する

今回はクラス「foo」を追加しました。

Foo.ts
import * as MU from "@util/messageUtil"

class Foo {
  constructor() {
    MU.info("Foo だよ!")
  }
}

export default Foo;

そして、main.tsでFooを呼び出します。

main.ts
import "module-alias/register";
import * as MU from "@util/messageUtil";
+import Foo from "@class/Foo";

MU.success("successです");
MU.info("infoです");
MU.task("taskです");
MU.warning("warningです");
MU.error("errorです");
+const foo = new Foo();

どこで呼び出すかがわかるようになりましたね!
image.png
実装は以下です。

messageUtil.ts
import dayjs from "dayjs";

const getTime = () => {
  return dayjs().format("HH:mm:ss:SSS");
};
const getLabel = () => {
  return `[${getScriptName()} ${getTime()}]`;
};

const getScriptName = () => {
  const error = new Error();
  const stack = error.stack || "";
  const stackLines = stack.split("\n");

  // スタックトレースの3行目から開始して、呼び出し元のコードを探します。
  // 最初の行はエラーメッセージで、2行目はこの関数の呼び出しです。
  // 必要に応じて開始インデックスを調整してください。
  let callerInfo = "";
  for (let i = 2; i < stackLines.length; i++) {
    if (stackLines[i].includes(__filename)) {
      // 現在のファイル名を含む行はスキップします
      continue;
    } else {
      callerInfo = stackLines[i];
      break;
    }
  }

  let callerLocation = "Unknown location";
  if (callerInfo) {
    callerLocation = callerInfo.split("(")[1].replace(")", "");
  }

  return callerLocation;
};

export const success = (msg: string) => {
  console.log("\x1b[32m%s \x1b[0m", `${getLabel()} SUCCESS: ${msg}`);
};

export const error = (msg: string) => {
  console.log("\x1b[31m%s \x1b[0m", `${getLabel()} ERROR: ${msg}`);
};

export const warning = (msg: string) => {
  console.log("\x1b[33m%s \x1b[0m", `${getLabel()} WARNING: ${msg}`);
};

export const task = (msg: string) => {
  console.log("\x1b[35m%s \x1b[0m", `${getLabel()} TASK: ${msg}`);
};

export const info = (msg: string) => {
  if (!msg) return;
  const lines = msg.split("\n").filter(Boolean);
  for (const line of lines) {
    console.log("\x1b[34m%s \x1b[0m", `${getLabel()} INFO: ${line}`);
  }
};

追記:サードパーティライブラリ

サードパーティライブラリを使用することでエラーメッセージを赤色など、好みの色で簡単に表示できます。例えば、chalkライブラリを使用してエラーメッセージを赤色で表示するには、次のようにします:

npm install chalk
example.ts
import chalk from "chalk";
console.error(chalk.red('This is an error message'));

まとめ

この記事では、一般的な白黒のconsole.log出力を、より視認性が高く、情報が把握しやすいカラフルなログに変える方法をご紹介しました。messageUtil.tsを用いて、ログの種類ごとに異なる色を割り当てることで、エラー、警告、情報などのログを一目で区別できるようになります。また、dayjsライブラリを使用してログにタイムスタンプを追加することで、ログが記録された正確な時刻を把握することが可能になります。

54
45
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
45