介绍
本文将介绍如何在 gRPC 微服务中添加 API 日志拦截器/中间件。
什么是日志拦截器/中间件?
日志拦截器会对每一个 API 请求记录日志。
我们将会使用 rk-boot 来启动 gRPC 服务。
请访问如下地址获取完整教程:
- https://rkdev.info/cn
- https://rkdocs.netlify.app/cn (备用)
安装
go get github.com/rookie-ninja/rk-boot
快速开始
rk-boot 默认集成如下两个开源库。
- uber-go/zap 作为底层的日志库。
- logrus 作为日志滚动。
1.创建 boot.yaml
为了验证,我们同时启动了 commonService。commonService 里包含了一系列通用 API。
详情: CommonService
grpc 默认会启动 grpc-gateway 来提供 Restful API 服务。在验证的时候,我们可以直接发送 Restful 请求。
---
grpc:
- name: greeter # Name of grpc entry
port: 8080 # Port of grpc entry
enabled: true # Enable grpc entry
commonService:
enabled: true # Enable common service for testing
interceptors:
loggingZap:
enabled: true # Enable logging interceptor
2.创建 main.go
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
)
// Application entrance.
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}
3.文件夹结构
$ tree
.
├── boot.yaml
├── go.mod
├── go.sum
└── main.go
0 directories, 4 files
3.验证
$ go run main.go
- 发送请求
$ curl -X GET localhost:8080/rk/v1/healthy
{"healthy":true}
- 验证日志
默认输出到 stdout&#x