在项目或类库编写中,一个友好的日志打印,能帮助开发者快速的定位到问题的存在,介绍一个好用的日志类库probe.gl
,类库地址 https://uber-web.github.io/probe.gl/docs
- 安装类库
npm install probe.gl
- 初始化日志类库
import { Log } from 'probe.gl'
const log = new Log({id:'我类库的名称'})
log.log('Hello world!')()
根据上面的示例我们就可以封装一个属于自己类库的方法,每次打印都会显示具体类库的名称,及日志,上面代码输出的结果就是
我类库的名称: Hello world
log实例中包含很多方法,这里介绍一下大家
- 常用的一些方法
import { Log,COLOR } from 'probe.gl'
const log = new Log({id:'my-app'})
// 打印消息,并给消息添加颜色,
log.log({message:'测试消息',color:COLOR.CYAN})()
// 设置日志优先级,并输出一个函数表达的结果,默认优先级为0
let expensiveFunction = ()=>`我是函数返回值`
log.log(1, () => `${expensiveFunction()}`)();
// 加入参数once 只打印一次
log.log({message:'只打印一次',color:COLOR.RED, once:true})()
log.log({message:'只打印一次',color:COLOR.RED, once:true})()
// 获取日志优先级,给日志加tag
const level = log.getPriority()
log.log({message:`等级为${level}`,color:COLOR.RED, tag:'myTarget'})()
// 打印信息,可以使用info,类似于console.info()
log.info('使用info')()
// 打印日志,并输出页面加载的时间
log.probe('页面加载完成后输出日志')()
// 打印警告信息
log.warn('警告信息warn')()
// 打印错误信息
log.error('错误消息error')()
// 断言输出日志,并抛出错误
const condition = '121'
log.assert(condition === '111','正确的数字是111')
// 变量舍弃提示
// 输出结果: `my-app: `name` is deprecated and will be removed in a later version. Use `姓名` instead`
log.deprecated('name','姓名')()
// 类似于console.table
log.table({a:1,b:2})()
// 类似于console.image
log.image(图片)
- 日志输出选项
Option | Type | Description |
---|---|---|
priority | Number | This probe will only "fire" if the log's current priority is greater than or equal to this value.defaults to 0, which means that the probe is executed / printed regardless of log level. |
time | Boolean | Add a timer since page load (default for Log.probe) |
once | Boolean | Logs this message only once (default for Log.warn, Log.once |
tag | String | Optional tag |
color | enum、String | Node.js only: Basic colors like green, blue and red are supported, currently only for console logging. For safe to use constants, use the COLOR enumeration, see below. |
background | enum、String | Node.js only: Colors the background of the character. |
网友评论