type Any = any
/**
* 创建 console 所需的 style 样式
* @param bgColor
* @param fontColor
*/
const createStyle = function(bgColor: string, fontColor = '#fff'): string {
return `color:${fontColor};background:${bgColor};padding:.3em .8em ;`
}
const SrcConsole = {
log: console.log,
warn: console.warn,
error: console.error
}
/**
* 参考 https://www.saninnsalas.com/keep-console-log-line-number-in-an-wrapper-function-that-also-add-an-prefix-text/
*/
export class Log {
private name = ''
private NameColor = createStyle('#409eff')
private createLevel(level: string): string {
return `%c${this.name}: %c${level}`
}
/**
* 获取日志实例
* @param name 日志的名称
* @param color 背景颜色, 默认 #409eff
* @param fontColor 字体颜色, 默认白色
*/
public static GetLogger(name: Any, color?: string, fontColor?: string) {
const l = new Log()
if (typeof name === 'string') {
l.name = name
} else {
l.name = name.constructor.name
}
if (color) {
l.NameColor = createStyle(color, fontColor)
}
return l
}
/**
* 提示 info message
*/
get info(): (...data: Any[]) => void {
return SrcConsole.log.bind(console, this.createLevel('info'),
this.NameColor,
createStyle('green'))
}
/**
* 错误 error message
*/
get error(): (...data: Any[]) => void {
return SrcConsole.error.bind(console, this.createLevel('error'),
this.NameColor,
createStyle('red'))
}
/**
* 警告 message
*/
get warn(): (...data: Any[]) => void {
return SrcConsole.warn.bind(console, this.createLevel('warn'),
this.NameColor,
createStyle('#ff9340'))
}
/**
* console.log, 输出原生的 console.log 信息
*/
public get log(): (...data: Any[]) => void {
return console.log.bind(console)
}
}
// 包装 console 日志
const log = Log.GetLogger('console', '#fecb44', '#000')
console.log = log.info
console.warn = log.warn
console.error = log.error
标签:vue,console,log,javascript,error,return,日志,string,name
From: https://www.cnblogs.com/whm-blog/p/17202362.html