使用 go iris 实现记录每个接口请求和请求时间

这篇文章将介绍两种方式记录接口请求和请求时间,一种是大家熟悉的中间件,另一种是用延迟函数来记录,对于小网站,我想应该足够了。Go iris 框架就不介绍了,这里有篇文章介绍:https://www.hrefs.cn/article/go-web-with-iris-examples

1. 串联处理器实现
func SystemLog(h context.Handler) context.Handler {
return func(ctx iris.Context) {
path := ctx.Path()
t := time.Now()
h(ctx)
elapsed := time.Since(t)
log.Printf("[%s] - %s", elapsed, path)
}
}

路由调用,将 SystemLog 函数放到 middleware 自建包中
app := iris.New()
app.Get("/articles", middleware.SystemLog(controller.ListArticles))

2. 延迟函数中间件实现
func Trace(ctx iris.Context) {
defer trace(ctx.Path())()
ctx.Next()
}

func trace(path string) func() {
start := time.Now()
return func() {
log.Printf("(%s) - %s", time.Since(start), path)
}
}

调用中间件
app := iris.New()
app.Use(middleware.Trace)

部署后记录日志如下:
2020/02/03 10:43:40 (2.249158ms) - /link/0de2eea0-81bf-4c82-b6a5-ffbcfe114e4e
2020/02/03 10:52:11 (1.858716ms) - /link/86bc9719-872a-495b-8f8f-69308aab45d7
2020/02/03 11:02:00 (6.349152ms) - /article/grpc-net-core-2.2-microservice
2020/02/03 11:03:28 (14.568769ms) - /login
2020/02/03 11:12:06 (1.179836ms) - /link/fe511b19-d4b2-45dd-b8eb-2f155b795a66
2020/02/03 11:12:08 (14.119466ms) - /
2020/02/03 11:14:57 (4.906175ms) - /articles
2020/02/03 11:15:09 (6.898602ms) - /article/go-web-with-iris-examples
2020/02/03 11:23:40 (116.189648ms) - /api/article/save
2020/02/03 11:23:40 (6.329704ms) - /api/article/list/15/1
2020/02/03 11:23:44 (1.549267ms) - /api/article/get/trace-url-and-times-with-go-iris
Posted by 何敏 on 2020-02-03 11:23:40