自定義一組漂亮的Log
引言
幾乎所有變成語言都有控制檯輸出Log,例如Android中Log,Golang中的log,及vlang中的log,系統輸出的日誌基本爲黑底白字。那麼我們可以通過什麼做法能夠實現彩色的日誌輸出呢?其實需要利用linux終端打印日誌的顏色設置即可。
linux終端下帶顏色輸入信息
參考原文:https://blog.csdn.net/subfate/article/details/43151213
輸入效果
實現
直接附上源碼
import time
struct Logx{
mut:
level int
}
pub fn new_logx()Logx{
return Logx{}
}
fn format(msg,open,close string)string{
return '\x1b[' + open + 'm' + msg + '\x1b[' + close + 'm'
}
fn format_green(msg string)string{
return format(msg,'32','39')
}
fn format_red(msg string)string{
return format(msg,'31','39')
}
fn format_yellow(msg string)string{
return format(msg,'33','39')
}
fn format_blue(msg string)string{
return format(msg,'34','39')
}
fn format_log(tag,msg string)string{
t:=time.now()
currentTime:=t.format()
return '[$tag] $currentTime $msg'
}
pub fn (l Logx)info(msg string){
target:=format_green(format_log('INFO',msg))
println('$target')
}
pub fn (l Logx)warn(msg string){
target:=format_yellow(format_log('WARN',msg))
println('$target')
}
pub fn (l Logx)debug(msg string){
target:=format_blue(format_log('DEBUG',msg))
println('$target')
}
pub fn (l Logx)error(msg string){
target:=format_red(format_log('ERROR',msg))
println('$target')
}
fn main(){
l:=new_logx()
l.info('我是一條logx')
l.warn('我是一條logx')
l.debug('我是一條logx')
l.error('我是一條logx')
}
最後
本文章會同步推送到微信公衆號【vlang中文社區】,搜索【vlang中文社區】或掃碼下方二維碼加入我們吧。