前端工具包之log美化

5,007 阅读2分钟

前言

我们在开发过程中,总会封装一些公共函数来作为我们的工具来简化代码或者复用代码,为此,我打算整理一下我日常工作中常用的一些封装的工具函数,本篇文章主要想实现下面的控制台输出效果,接下来就来看看吧。

系列文章

1.前端工具包之深浅拷贝

2.前端工具包之日期格式化

3.前端工具包之防抖函数

4.前端工具包之小工具

5.前端工具包之log美化

背景

作为一个前端开发者,肯定避免不了F12的控制台调试,而在前端调试过程中我们会经常写console.log来将我们想调试的部分在控制台打印输出,像下面这种

但是这种调试如果过多了我们很可能分不清上下文或者某一个函数内的打印情况,所以有时候我会额外的打印分割线和说明,如

这样虽然相对比较清晰了,但是有时候由于行数多颜色相同,还是不方便区分也不够美观。由于我是个vue开发者,然后无意中发现了一个这样的输出

哎,好像发现了新大陆(我知道好多人可能会吐槽,这不就是浏览器打印彩色字体嘛,噗,闻道有先后,恕我知道的比较晚哈)

出于好奇我点进去这个插件的sources,发现了一段这样的代码

    src_bridge.on('log-detected-vue', () => {
      console.log(
        `%c vue-devtools %c Detected Vue v${Vue.version} %c`,
        'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
        'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
        'background:transparent'
      )
    })

原来console有这么多方法呀,如什么分组啊,dir,table都可以针对不同输出来输出不同的内容,感兴趣的可以去搜一下这里因为只想实现一个类似的工具打印,所以只介绍一下log的格式化输出功能

格式化输出

log 的格式化输出有几个占位符

占位符 含义
%s 字符串输出
%d or %i 整数输出
%f 浮点数输出
%o 打印javascript对象,可以是整数、字符串以及JSON数据
%c 自定义输出样式

示例1

console.log("欢迎%s和%s两位新同学",'小明','小张');

console.log("圆周率整数部分:%d,带上小数是:%f",3.1415,3.1415);

直接打开f12输入上面两行就会得到下面的输出

示例2

console.log("%c我是绿色倾斜的字体", "color: green; font-style: italic");

console.log("%c 我是3D样式", " text-shadow: 0 1px 0 #ccc,0 2px 0 #c9c9c9,0 3px 0 #bbb,0 4px 0 #b9b9b9,0 5px 0 #aaa,0 6px 1px rgba(0,0,0,.1),0 0 5px rgba(0,0,0,.1),0 1px 3px rgba(0,0,0,.3),0 3px 5px rgba(0,0,0,.2),0 5px 10px rgba(0,0,0,.25),0 10px 10px rgba(0,0,0,.2),0 20px 20px rgba(0,0,0,.15);font-size:5em");

console.log('%c色彩带 ', 'background-image:-webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );color:transparent;-webkit-background-clip: text;font-size:5em;');

console.log('%c我是带有背景的输出.', 'color: #fff; background: #f40; font-size: 24px;');

复制上面的到控制台执行,你会得到如下输出

怎么样,是不是很酷呢,现在看来,类似vue-devtools 打印的这种文本是不是很好理解呢,到现在,咱们就可以开始实现自己的彩色输出工具函数的封装了。下面看代码

工具封装

先简要分析一下,现在大多数库都会提供几个状态的色值,如 element会提供primary,success,info,warning,danger等类似的默认色值,而且我们还想实现非状态的自定义颜色,那么我们就需要一个辅助的获取颜色值的函数,和一个真正输出的函数,而且这个工具库还得有一些快捷输出,

1.首先是获取颜色值的辅助函数,该函数有6个默认样式的颜色,也可以直接传入标准的颜色字符来返回。

/**
 * @description 返回这个样式的颜色值
 * @param {String} type 样式名称 [ primary | success | warning | danger | info ]
 */
function typeColor (type = 'default') {
  let color = ''
  switch (type) {
    case 'primary':
      color = '#2d8cf0'
      break
    case 'success':
      color = '#19be6b'
      break
    case 'info':
      color = '#909399'
      break
    case 'warning':
      color = '#ff9900'
      break
    case 'danger':
      color = '#f03f14'
      break
    case 'default':
      color = '#35495E'
      break
    default:
      color = type
      break
  }
  return color
}

2.通用颜色的打印方法,这里我们给函数起名为print,直译为打印

const log = {} // 定义一个对象

/**
 * 打印方法
 * @param text 输出文本
 * @param type 输出样式,可以是6个状态值,也可以是自定义颜色
 * @param back 是否将色值应用于背景色
 */
log.print = function (text, type = 'default', back = false) {
  if (typeof text === 'object') { // 如果是对象则调用打印对象方式
    console.dir(text)
    return
  }
  if (back) { // 如果是打印带背景图的
    console.log(
      `%c ${text} `,
      `background:${typeColor(type)}; padding: 2px; border-radius: 4px;color: #fff;`
    )
  } else {
    console.log(
      `%c ${text} `,
      `color: ${typeColor(type)};`
    )
  }
}

这里做一个判定,因为我们输出的可能为对象,如果是对象则直接用dir方法打印,如果是字符串,则再根据配置来输出,做个简单的测试如下

// 彩色字体
log.print('=======彩色字体======')
log.print('this is default log')
log.print('this is primary log','primary')
log.print('this is success log','success')
log.print('this is info log','info')
log.print('this is warning log','warning')
log.print('this is danger log','danger')
log.print('this is custom log','#df85ff')
// 背景底色
log.print('=======背景底色======')
log.print('this is primary log','primary',true)
log.print('this is success log','success',true)
log.print('this is info log','info',true)
log.print('this is warning log','warning',true)
log.print('this is danger log','danger',true)
log.print('this is custom log','#df85ff',true)

这么看输出,是不是好看多了。接下来我们仿照vue-devtools来在扩展一个方法,参考上面的源码改写一下输出不同的类型颜色即可

/**
 * 漂亮的输出
 * @param title 前面的标题
 * @param text 输出文本
 * @param type 输出样式,可以是6个状态值,也可以是自定义颜色
 */
log.pretty = function (title, text, type = 'primary') {
  console.log(
    `%c ${title} %c ${text} %c`,
    `background:${typeColor(type)};border:1px solid ${typeColor(type)}; padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`,
    `border:1px solid ${typeColor(type)}; padding: 1px; border-radius: 0 4px 4px 0; color: ${typeColor(type)};`,
    'background:transparent'
  )
}

我们这里的输出稍微区别一下vue-devtools,采用前带背景后面为白色实现,如有想法可以根据实际自行改变。这里输出看看效果。

// 漂亮的输出
log.print('=======漂亮的输出======')
log.pretty('title','this is primary')
log.pretty('title','this is default','default')
log.pretty('title','this is success','success')
log.pretty('title','this is info','info')
log.pretty('title','this is warning','warning')
log.pretty('title','this is danger','danger')
log.pretty('title','this is custom','#df85ff')
log.pretty('bin-ui','https://wangbin3162.gitee.io/bin-ui/')

就会得到如下的输出

怎么样,是不是很有个性呢,有了颜色做区分,以后打印就会更加灵活美观了。

最后我们再给我们的工具丰富一下几个接口函数,因为我们想快速打印不同状态的字体时总得输入type的类型很不友好,我们可以这样写

log.primary = function (text, back = false) {
  this.print(text, 'primary', back)
}
log.success = function (text, back = false) {
  this.print(text, 'success', back)
}
log.info = function (text, back = false) {
  this.print(text, 'info', back)
}
log.warning = function (text, back = false) {
  this.print(text, 'warning', back)
}
log.danger = function (text, back = false) {
  this.print(text, 'danger', back)
}

ps 实际上就相当于快捷调用了print方法,只是无须设置颜色值了,输出依然是第一个例子那种

log.print('=======便捷输出彩色文字======')
log.primary('this is primary')
log.success('this is success')
log.info('this is info')
log.warning('this is warning')
log.danger('this is danger')

log.print('=======便捷输出彩色背景文字======')
log.primary('this is primary back',true)
log.success('this is success back',true)
log.info('this is info back',true)
log.warning('this is warning back',true)
log.danger('this is danger back',true)

到这里整个log的工具就封装完成了,把以上代码组合一下就可以拿到自己的项目中使用啦,这里说一下我自己的vue组件库 bin-ui ,你打开官网文档也会发现一个类似的输出链接到文档地址

其实组件库已经集成了这个小工具包,直接使用this.$log.print就可以快速调用啦。


相关链接

个人主页 | bin-ui | bin-admin