在go裏面,雖然有log模塊,但是該模塊提供的功能並不強,譬如就沒有我們常用的level log功能,但是自己實現一個log模塊也並不困難。
對於log的level,我們定義如下:
const (
LevelTrace = iota
LevelDebug
LevelInfo
LevelWarn
LevelError
LevelFatal
)
相應的,提供如下幾個函數:
func Trace(format string, v ...interface{})
func Debug(format string, v ...interface{})
func Info(format string, v ...interface{})
func Warn(format string, v ...interface{})
func Error(format string, v ...interface{})
func Fatal(format string, v ...interface{})
另外,對於一個log,我們可能將其寫入不同的地方,譬如可能直接輸出到stdout,或者寫文件,或者寫socket,在創建特定logger的時候,我們需要指定對應的handler,用來實現不同的寫入方式。
handler的定義如下:
type Handler interface {
Write(p []byte) (n int, err error)
Close() error
}
我們可以參考python的log模塊,實現幾個通用的handler,譬如StreamHandler,FileHandler,TimeRotatingFileHandler。
log模塊的實現https://github.com/siddontang/golib/tree/master/log。