企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 使用context包进行日志记录 本节将展示如何在各种函数间传递log操作。使用Go标准库中的context包是在函数之间传递和取消变量的绝佳方式。本节将探讨如何使用该方案在函数之间分配变量以进行日志记录。 本节使用到了上节中提到的apex库。 ### 实践 1. 获取第三方库: ``` go get github.com/apex/log ``` 2. 建立log.go: ``` package context import ( "context" "github.com/apex/log" ) type key int const logFields key = 0 func getFields(ctx context.Context) *log.Fields { fields, ok := ctx.Value(logFields).(*log.Fields) if !ok { f := make(log.Fields) fields = &f } return fields } // FromContext 接收一个log.Interface和context // 然后返回由context对象填充的log.Entry指针 func FromContext(ctx context.Context, l log.Interface) (context.Context, *log.Entry) { fields := getFields(ctx) e := l.WithFields(fields) ctx = context.WithValue(ctx, logFields, fields) return ctx, e } // WithField 将log.Fielder添加到context func WithField(ctx context.Context, key string, value interface{}) context.Context { return WithFields(ctx, log.Fields{key: value}) } // WithFields 将log.Fielder添加到context func WithFields(ctx context.Context, fields log.Fielder) context.Context { f := getFields(ctx) for key, val := range fields.Fields() { (*f)[key] = val } ctx = context.WithValue(ctx, logFields, f) return ctx } ``` 3. 建立collect.go: ``` package context import ( "context" "os" "github.com/apex/log" "github.com/apex/log/handlers/text" ) // Initialize调用3个函数来设置,然后在操作完成之前记录日志 func Initialize() { log.SetHandler(text.New(os.Stdout)) //初始化context ctx := context.Background() // 将context与log.Log建立联系 ctx, e := FromContext(ctx, log.Log) ctx = WithField(ctx, "id", "123") e.Info("starting") gatherName(ctx) e.Info("after gatherName") gatherLocation(ctx) e.Info("after gatherLocation") } func gatherName(ctx context.Context) { ctx = WithField(ctx, "name", "Go Cookbook") } func gatherLocation(ctx context.Context) { ctx = WithFields(ctx, log.Fields{"city": "Seattle", "state": "WA"}) } ``` 4. 建立main.go: ``` package main import "github.com/agtorre/go-cookbook/chapter4/context" func main() { context.Initialize() } ``` 5. 这会输出: ``` INFO[0000] starting id=123 INFO[0000] after gatherName id=123 name=Go Cookbook INFO[0000] after gatherLocation city=Seattle id=123 name=Go Cookbook state=WA ``` ### 说明 context包的使用在databases包和HTTP包中都可以看到。本节将log附加到context并将其用于记录日志以达到并发安全的目的。我们通过在方法中传递context来同时传递附加于其上的属性,以达到在最终调用位置记录日志的目的。 这些修改了存储在上下文中的单个值,并提供了使用context的另一个好处:可以执行取消和超时操作,并且线程安全。 * * * * 学识浅薄,错误在所难免。欢迎在群中就本书提出修改意见,以飨后来者,长风拜谢。 Golang中国(211938256) beego实战(258969317) Go实践(386056972)