在 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() 或createTempTable()。
如果代码编排在您的主应用程序中,并且包仅提供简单的操作。作为函数调用的一部分,将错误返回给用户会容易得多。
它还可以让其他人更容易重复使用您的包,因为它们具有简单的操作和开放用户以其他方式使用它们而不是您想要的。