上一篇中咱们将文件日志库基本实现了,咱们如今再讲console日志库实现,那咱们的日志库也基本就能够完成了。函数
新建console.go
,把咱们console日志库也实现了。由于console日志库只是将日志输出到终端里面。测试
package hm_log
import (
"fmt"
"os"
)
type ConsoleLog struct{}
func NewConsoleLog() (logCon Log, err error) {
logCon = &ConsoleLog{}
return
}
func (c *ConsoleLog) Debug(format string, args ...interface{}) {
}
...
func (c *ConsoleLog) Warn(format string, args ...interface{}) {
}
...
func (c *ConsoleLog) Close() {
}
复制代码
可是打印到终端的日志和文件写入的日志是同样,再写一遍也是累,直接将以前的函数写到util.go
中,分开调用就能够了:this
func writeLog(file *os.File, level int, format string, args... interface{} {
now := time.Now()
nowStr := now.Format("2006-01-02 15:04:05.999")
// 这个数字格式是固定的不能改变的,可是-和:能够更换
levelStr := LogLevelString(level)
fileName, funcName, lineNo := GetLineInfo()
//因为这里返回的是全路径的,可是咱们不须要,因此咱们只须要文件名以及相关的便可
fileName = path.Base(fileName)
funcName = path.Base(funcName)
msg := fmt.Sprintf(format, args...)
fmt.Fprintf(file, "%s %s [%s/%s:%d] %s\n", nowStr, levelStr, fileName, funcName, lineNo, msg)
}
复制代码
file.go
spa
func (f *FileLog) Debug(format string, args ...interface{}) {
writeLog(f.file, DebugLevel, format, args...)
}
复制代码
console.go
日志
func (c *ConsoleLog) Debug(format string, args ...interface{}) {
writeLog(os.Stdout, DebugLevel, format, args...)
}
...
func (c *ConsoleLog) Warn(format string, args ...interface{}) {
writeLog(os.Stdout, WarnLevel, format, args...)
}
...
复制代码
这样咱们console日志库就完成了,而后咱们来测试一下。 在log_test.go
来测试咱们写的文件日志库。code
package log
import (
"testing"
)
func TestFileLog(t *testing.T) {
log := NewFileLog(".", "test")
log.Debug("this is file debub test")
log.Warn("this is file warn test")
log.Close()
}
func TestConsoleLog(t *testing.T) {
log := NewConsoleLog()
log.Debug("this is file debub test")
log.Warn("this is file warn test")
}
复制代码
go test一下,看看咱们终端输出是否和咱们以前定义的日志格式同样。orm
注意string
go test
默认执行当前目录下以xxx_test.go
的测试文件。 go test -v
能够看到详细的输出信息。 go test -v xxx_test.go
指定测试单个文件,可是该文件中若是调用了其它文件中的模块会报错。 指定某个测试函数运行: go test -v -test.run Testxxx
注意: 该测试会测试包含该函数名的全部函数,即若是待测试的函数名是TestSyncResourceQuota
,那么指令go test -v -test.run TestSyncResourceQuota
会测试包含该函数名的全部函数(好比TestSyncResourceQuotaSpecChange
、TestSyncResourceQuotaSpecHardChange
等函数)it