美化控制台日志——让你的 `console.log` 变得更炫酷

背景故事

在一次开发过程中,我意识到控制台日志虽然实用,但其单一的输出样式常常让调试工作变得乏味。为了提升调试的效率和视觉体验,我决定设计一个美化控制台输出的工具。最终,这个工具不仅在我的个人项目中发挥了作用,还引起了团队的关注。领导对这种日志美化的效果非常满意,并建议将其整合到我们的公共工具库中,以便团队其他成员使用。

本文将详细介绍如何实现一个美化控制台输出的工具,并展示如何在 Vue 3 项目中应用这一技术。
在这里插入图片描述

console 简介

console 是 JavaScript 内置的调试工具对象,提供了多种方法用于输出日志、警告和错误信息。常用的 console 方法包括:

  • console.log():输出一般信息。
  • console.info():输出信息,样式与 console.log 类似。
  • console.warn():输出警告信息,通常带有黄色背景。
  • console.error():输出错误信息,通常带有红色背景。
  • console.table():以表格形式展示数据,适合显示数组和对象。

例如,使用 console.table() 输出员工信息列表:

const employees = [
    { name: 'Alice', position: 'Developer', age: 30 },
    { name: 'Bob', position: 'Designer', age: 25 }
];
console.table(employees);

在这里插入图片描述

虽然这些方法提供了基本的输出功能,但它们的样式和信息展示方式较为单一。为了让日志输出更加直观和美观,我们可以利用 console.log 的 CSS 样式功能来实现自定义样式。

技术方案

console.log 支持多种参数类型,包括字符串、数字、对象等。更重要的是,它支持占位符,尤其是 %c 占位符可以用来应用 CSS 样式,从而让日志信息更具可读性。例如:

console.log('%c Stylish Log Message', 'color: blue; font-size: 16px;');
实现美化控制台日志

下面我们实现一个 prettyLog 方法,用于美化控制台日志的输出:

// src/utils/prettyLog.ts

const isEmpty = (value: any) => {
  return value == null || value === undefined || value === '';
};

const prettyPrint = (title: string, text: string, color: string) => {
  console.log(
    `%c ${title} %c ${text} %c`,
    `background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
    `border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
    'background:transparent'
  );
};

const titlePrint = (title: string) => {
  console.log(`%c ${title}`, 'font-size: 20px; font-weight: bold; color: #333;');
};

const tablePrint = (title: string, data: any[]) => {
  console.groupCollapsed(title);
  console.table(data);
  console.groupEnd();
};

const imagePrint = (title: string, url: string, scale = 1) => {
  const img = new Image();
  img.crossOrigin = 'anonymous';
  img.onload = () => {
    const c = document.createElement('canvas');
    const ctx = c.getContext('2d');
    if (ctx) {
      c.width = img.width;
      c.height = img.height;
      ctx.drawImage(img, 0, 0);
      const dataUri = c.toDataURL('image/png');

      console.log(
        `%c ${title}`,
        `font-size: 1px;
         padding: ${Math.floor((img.height * scale) / 2)}px ${Math.floor((img.width * scale) / 2)}px;
         background-image: url(${dataUri});
         background-repeat: no-repeat;
         background-size: ${img.width * scale}px ${img.height * scale}px;
         color: transparent;
        `
      );
    }
  };
  img.src = url;
};

const prettyLog = () => {
  const info = (textOrTitle: string, content = '') => {
    const title = isEmpty(content) ? 'Info' : textOrTitle;
    const text = isEmpty(content) ? textOrTitle : content;
    prettyPrint(title, text, '#909399');
  };

  const error = (textOrTitle: string, content = '') => {
    const title = isEmpty(content) ? 'Error' : textOrTitle;
    const text = isEmpty(content) ? textOrTitle : content;
    prettyPrint(title, text, '#F56C6C');
  };

  const warning = (textOrTitle: string, content = '') => {
    const title = isEmpty(content) ? 'Warning' : textOrTitle;
    const text = isEmpty(content) ? textOrTitle : content;
    prettyPrint(title, text, '#E6A23C');
  };

  const success = (textOrTitle: string, content = '') => {
    const title = isEmpty(content) ? 'Success' : textOrTitle;
    const text = isEmpty(content) ? textOrTitle : content;
    prettyPrint(title, text, '#67C23A');
  };

  const title = (text: string) => {
    titlePrint(text);
  };

  const table = (title: string, data: any[]) => {
    tablePrint(title, data);
  };

  const image = (title: string, imageUrl: string) => {
    imagePrint(title, imageUrl);
  };

  return {
    info,
    error,
    warning,
    success,
    title,
    table,
    image
  };
};

// 只在开发环境中使用
export const log =
  import.meta.env.MODE === 'development'
    ? prettyLog()
    : {
        info: () => {},
        error: () => {},
        warning: () => {},
        success: () => {},
        title: () => {},
        table: () => {},
        image: () => {}
      };
在 Vue 3 项目中的应用

为了在 Vue 3 项目中方便地使用这个美化 console.log 的工具,我们可以将其封装成工具函数,并确保它仅在开发环境中生效:

<script lang="ts" setup>
// 引入美化日志工具函数
import { log } from '@/utils/prettyLog';

// 打印标题
log.title('开发日志');

// 输出普通信息
log.info('这是一个普通信息', '详细描述');

// 输出警告信息
log.warning('这是一个警告信息', '注意事项');

// 输出成功信息
log.success('这是一个成功信息', '操作成功');

// 输出错误信息
log.error('这是一个错误信息', '操作失败');

// 输出表格
log.table('用户列表', [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
]);

// 输出图片
log.image('项目Logo', 'https://example.com/logo.png');
</script>

<template>
  <div>
    <!-- 组件内容 -->
  </div>
</template>
总结

通过使用 prettyLog 工具函数,我们不仅可以让控制台日志变得更加美观和易于阅读,还能在开发过程中提高调试的效率。这种美化的日志输出方式,能够帮助团队更好地理解代码执行情况,并使开发过程更加有趣。

希望这篇文章能为大家提供一些实用的技巧,让你们的调试过程更加高效和愉快。如果你有任何问题或建议,请随时分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值