前言
logit 是一個簡單易用並且是基於級別控制的日誌庫,可以應用於所有的 GoLang 應用程序中。
開源地址:gitee.com/FishGoddess/logit
核心特性
部署方式
需要依賴於Golang 運行環境。
第一步:Go modules
<code>$ go get -u github.com/FishGoddess/logit/<code>
可以對go.mod 文件進行直接編輯 ,然後再執行 go build。
<code>module your_project_name
go 1.14
require (
github.com/FishGoddess/logit v0.0.10
)/<code>
第二步:Go path
<code>$ go get -u github.com/FishGoddess/logit/<code>
logit 沒有任何其他額外的依賴,純使用 Golang 標準庫 完成。
<code>package main
import (
"math/rand"
"strconv"
"time"
"github.com/FishGoddess/logit"
)
func main() {
// Log as you want.
logit.Debug("I am a debug message! But I will not be logged in default level!")
logit.Info("I am an info message!")
logit.Warn("I am a warn message!")
logit.Error("I am an error message!")
// Change logger level.
logit.ChangeLevelTo(logit.DebugLevel)
// If you want to output log with file info, try this:
logit.EnableFileInfo()
logit.Info("Show file info!")
// If you have a long log and it is made of many variables, try this:
// The msg is the return value of msgGenerator.
logit.DebugFunction(func() string {
// Use time as the source of random number generator.
r := rand.New(rand.NewSource(time.Now().Unix()))
return "debug rand int: " + strconv.Itoa(r.Intn(100))
})
}/<code>
性能測試
<code>$ go test -v ./_examples/benchmarks_test.go -bench=. -benchtime=1s/<code>
測試文件
下載地址:gitee.com/FishGoddess/logit/blob/master/_examples/benchmarks_test.go
測試環境:I7-6700HQ CPU @ 2.6 GHZ,16 GB RAM
備註
1. 輸出文件信息會有運行時操作(runtime.Caller 方法),非常影響性能, 但是這個功能感覺還是比較實用的,尤其是在查找錯誤的時候,所以我們還是加了這個功能! 如果你更在乎性能,那我們也提供了一個選項可以關閉文件信息的查詢!
2. v0.0.7 及以前版本的日誌輸出使用了 fmt 包的一些方法,經過性能檢測發現這些方法存在大量使用反射的 行為,主要體現在對參數 v interface{} 進行類型檢測的邏輯上,而日誌輸出都是字符串,這一個 判斷是可以省略的,可以減少很多運行時操作時間!v0.0.8 版本開始使用了更有效率的輸出方式!
3. 經過對 v0.0.8 版本的性能檢測,發現時間格式化操作消耗了接近一半的處理時間, 主要體現在 time.Time.AppendFormat 的調用上。目前正在思考優化方案,或許會在之後的版本中解決!
閱讀更多 IT實戰聯盟 的文章