我在这里为任何对类似解决方案感兴趣的人发布我的答案。
我所做的是复制标准日志包 (src/log/log.go) 并扩展它。获得一个已经完成标准记录器所做的所有事情以及您希望它做的任何其他事情的全局记录器再简单不过了!在这种情况下,支持分级日志记录。
我必须做的唯一修改:
type Logger struct {
mu sync.Mutex // ensures atomic writes; protects the following fields
prefix string // prefix to write at beginning of each line
flag int // properties
out io.Writer // destination for output
buf []byte // for accumulating text to write
level int // One of DEBUG, ERROR, INFO
}
只添加了最后一行。日志包设置了一个全局变量 std,然后可以使用该变量从包中的任何函数访问结构字段。
接下来我为不同的日志级别添加了常量:
const (
DEBUG = 1 << iota
INFO
ERROR
)
接下来我添加了我的函数:
(注意:ct 是 https://github.com/seago/go-colortext 包,它允许在 Windows 上为控制台文本着色。所以这里的错误都以红色打印)
func Error(v ...interface{}) {
if std.level <= ERROR {
ct.ChangeColor(ct.Red, true, ct.None, false)
s := fmt.Sprintf("ERROR: %v", v...)
std.Output(2, s)
ct.ResetColor()
}
}
func Info(format string, v ...interface{}) {
if std.level <= INFO {
s := fmt.Sprintf("INFO: "+format, v...)
std.Output(2, s)
}
}
func Debug(v ...interface{}) {
if std.level <= DEBUG {
s := fmt.Sprintf("DEBUG: %v", v...)
std.Output(2, s)
}
}
func SetLogLevel(lvl int) {
std.level = lvl
}
就是这样!有了它,我现在可以通过简单地导入修改后的包而不是标准日志包来使用它并注销:
import (
"errors"
"tryme/log"
)
func main() {
log.SetLogLevel(log.INFO)
log.Info("This is a test Info")
err := errors.New("This is a test error!!!")
log.Error(err)
log.Debug("Testing debugging") // won't be printed with log.INFO
}
这当然只是一个演示,可以通过更多日志级别、输出格式等轻松扩展。
您可以使用标准日志包提供的所有功能,例如 SetOutput 写入文件或 MultiWriter 写入文件和控制台等。