上一篇中我们将文件日志库基本实现了,我们现在再讲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
中,分开调用就可以了:
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
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
来测试我们写的文件日志库。
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一下,看看我们终端输出是否和我们之前定义的日志格式一样。
注意
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
等函数)