2 回答

TA貢獻1873條經驗 獲得超9個贊
有些 go lib 使用這樣的日志記錄
在你的包中確定一個記錄器接口
type Yourlogging interface{
Errorf(...)
Warningf(...)
Infof(...)
Debugf(...)
}
并為此接口定義一個變量
var mylogger Yourlogging
func SetLogger(l yourlogging)error{
mylogger = l
}
在您的函數中,您可以調用它們進行日志記錄
mylogger.Infof(..)
mylogger.Errorf(...)
你不需要實現接口,但是你可以使用實現這個接口的他們
for example:
SetLogger(os.Stdout) //logging output to stdout
SetLogger(logrus.New()) // logging output to logrus (github.com/sirupsen/logrus)

TA貢獻1886條經驗 獲得超2個贊
在 Go 中,您會看到一些庫實現了日志接口,就像其他答案所建議的那樣。但是,例如,如果您以不同的方式構建應用程序,則可以完全避免您的包需要記錄。
例如,在您鏈接的示例應用程序中,您的主應用程序運行時調用idleexacts.Run(),它會啟動此函數。
// startLoop starts workload using passed settings and database connection.
func startLoop(ctx context.Context, log log.Logger, pool db.DB, tables []string, jobs uint16, minTime, maxTime time.Duration) error {
rand.Seed(time.Now().UnixNano())
// Increment maxTime up to 1 due to rand.Int63n() never return max value.
maxTime++
// While running, keep required number of workers using channel.
// Run new workers only until there is any free slot.
guard := make(chan struct{}, jobs)
for {
select {
// Run workers only when it's possible to write into channel (channel is limited by number of jobs).
case guard <- struct{}{}:
go func() {
table := selectRandomTable(tables)
naptime := time.Duration(rand.Int63n(maxTime.Nanoseconds()-minTime.Nanoseconds()) + minTime.Nanoseconds())
err := startSingleIdleXact(ctx, pool, table, naptime)
if err != nil {
log.Warnf("start idle xact failed: %s", err)
}
// When worker finishes, read from the channel to allow starting another worker.
<-guard
}()
case <-ctx.Done():
return nil
}
}
}
這里的問題是你的邏輯的所有編排都發生在你的包內部。相反,這個循環應該在你的主應用程序中運行,并且這個包應該為用戶提供簡單的操作,例如selectRandomTable()or createTempTable()。
如果代碼編排在您的主應用程序中,并且包僅提供簡單的操作。作為函數調用的一部分,將錯誤返回給用戶會容易得多。
它還可以使您的包更容易被其他人重用,因為它們具有簡單的操作并且可以讓用戶以超出您預期的其他方式使用它們。
- 2 回答
- 0 關注
- 140 瀏覽
添加回答
舉報