go開發屬於自己的日誌庫-控制檯日誌實現
阿新 • • 發佈:2018-12-20
上一篇中我們將檔案日誌庫基本實現了,我們現在再講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
等函式)