上一篇中咱們將文件日誌庫基本實現了,咱們如今再講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