当前位置:网站首页>Grpc: how to add API log interceptors / Middleware?
Grpc: how to add API log interceptors / Middleware?
2022-06-24 03:19:00 【Trespass 】
Introduce
This article will show you how to gRPC Add in microservice API Log interceptor / middleware .
What is a log interceptor / middleware ?
Log interceptors will be used for every API Request logging .
We will use rk-boot To start up gRPC service .
Please visit the following address for a complete tutorial :https://rkdev.info/cnhttps://rkdocs.netlify.app/cn ( spare )
install
go get github.com/rookie-ninja/rk-boot go get github.com/rookie-ninja/rk-grpc
Quick start
rk-boot By default, the following two open source libraries are integrated .
- uber-go/zap As the underlying log Library .
- logrus Scroll as log .
1. establish boot.yaml
In order to verify , We started at the same time commonService.commonService It contains a series of general API.
details : CommonService
grpc It starts by default grpc-gateway To provide Restful API service . At the time of verification , We can send... Directly Restful request .
---
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 interceptor2. establish main.go
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
_ "github.com/rookie-ninja/rk-grpc/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. Folder structure
$ tree . ├── boot.yaml ├── go.mod ├── go.sum └── main.go 0 directories, 4 files
4. verification
$ go run main.go
- Send a request
$ curl -X GET localhost:8080/rk/v1/healthy
{"healthy":true}- Verify the log Default output to stdout( Console ).
The following log format is from rk-query , Users can also choose JSON Format , We'll talk about .
------------------------------------------------------------------------
endTime=2021-07-09T23:44:09.81483+08:00
startTime=2021-07-09T23:44:09.814784+08:00
elapsedNano=46065
timezone=CST
ids={"eventId":"67d64dab-f3ea-4b77-93d0-6782caf4cfee"}
app={"appName":"rk-demo","appVersion":"master-f414049","entryName":"greeter","entryType":"GrpcEntry"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}
payloads={"grpcMethod":"Healthy","grpcService":"rk.api.v1.RkCommonService","grpcType":"unaryServer","gwMethod":"","gwPath":"","gwScheme":"","gwUserAgent":""}
error={}
counters={}
pairs={"healthy":"true"}
timing={}
remoteAddr=localhost:58205
operation=/rk.api.v1.RkCommonService/Healthy
resCode=OK
eventStatus=Ended
EOEChange the log format
We can modify boot.yaml To modify the log format .
At present, we support json and console Two formats , The default is console.
By modifying the eventLoggerEncoding The value of is json, We can output the log as JSON Format .
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
zapLoggerEncoding: "json" # Override to json format, option: json or console
eventLoggerEncoding: "json" # Override to json format, option: json or consoleModify log path
By modifying the eventLoggerOutputPaths Value , You can specify an output path .
The log defaults to 1GB after , For cutting , And compress .
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
zapLoggerOutputPaths: ["logs/app.log"] # Override output paths, option: json or console
eventLoggerOutputPaths: ["logs/event.log"] # Override output paths, option: json or consoleConcept
Log interceptor verified , Let's talk about it in detail rk-boot What are the functions of the provided log interceptors .
We need to understand two concepts in advance .
- EventLogger
- ZapLogger
ZapLogger
Used to record errors / Detailed log , This user can get RPC Called ZapLogger example , Log writing , Every RPC Of ZapLogger All instances contain the current RequestId.
2021-07-09T23:52:13.667+0800 INFO boot/grpc_entry.go:694 Bootstrapping grpcEntry. {"eventId": "9bc192fb-567c-45d4-8775-7a097b0dab04", "entryName": "greeter", "entryType": "GrpcEntry", "grpcPort": 8080, "commonServiceEnabled": true, "tlsEnabled": false, "gwEnabled": true, "reflectionEnabled": false, "swEnabled": false, "tvEnabled": false, "promEnabled": false, "gwClientTlsEnabled": false, "gwServerTlsEnabled": false}EventLogger
RK The starter puts each RPC Request as Event, And use rk-query Medium Event Type to log .
Field | details |
|---|---|
endTime | End time |
startTime | Starting time |
elapsedNano | Event Time cost (Nanoseconds) |
timezone | The time zone |
ids | contain eventId, requestId and traceId. If the original data interceptor is activated , perhaps event.SetRequest() Called by user , new RequestId Will be used , meanwhile eventId And requestId It will be as like as two peas. . If the call chain interceptor is started ,traceId Will be recorded . |
app | contain appName, appVersion, entryName, entryType. |
env | contain arch, az, domain, hostname, localIP, os, realm, region. realm, region, az, domain Field . These fields come from system environment variables (REALM,REGION,AZ,DOMAIN). "*" Indicates that the environment variable is empty . |
payloads | contain RPC Related information . |
error | Contains errors . |
counters | adopt event.SetCounter() To operate . |
pairs | adopt event.AddPair() To operate . |
timing | adopt event.StartTimer() and event.EndTimer() To operate . |
remoteAddr | RPC Remote address . |
operation | RPC name . |
resCode | RPC Return code . |
eventStatus | Ended perhaps InProgress |
------------------------------------------------------------------------
endTime=2021-07-09T23:44:09.81483+08:00
startTime=2021-07-09T23:44:09.814784+08:00
elapsedNano=46065
timezone=CST
ids={"eventId":"67d64dab-f3ea-4b77-93d0-6782caf4cfee"}
app={"appName":"rk-demo","appVersion":"master-f414049","entryName":"greeter","entryType":"GrpcEntry"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}
payloads={"grpcMethod":"Healthy","grpcService":"rk.api.v1.RkCommonService","grpcType":"unaryServer","gwMethod":"","gwPath":"","gwScheme":"","gwUserAgent":""}
error={}
counters={}
pairs={"healthy":"true"}
timing={}
remoteAddr=localhost:58205
operation=/rk.api.v1.RkCommonService/Healthy
resCode=OK
eventStatus=Ended
EOELog interceptor options
name | describe | type | The default value is |
|---|---|---|---|
grpc.interceptors.loggingZap.enabled | Start log interceptor | boolean | false |
grpc.interceptors.loggingZap.zapLoggerEncoding | Log format :json perhaps console | string | console |
grpc.interceptors.loggingZap.zapLoggerOutputPaths | Log file path | []string | stdout |
grpc.interceptors.loggingZap.eventLoggerEncoding | Log format :json perhaps console | string | console |
grpc.interceptors.loggingZap.eventLoggerOutputPaths | Log file path | []string | false |
obtain RPC Log instance
every time RPC When asked to come in , The interceptor will RequestId( When the original data interceptor is started ) Inject into the log instance .
let me put it another way , every last RPC request , There will be a new Logger example . Let's see how for one RPC request , Record ZapLogger journal .
adopt rkgrpcctx.GetLogger(ctx) Method to obtain the log instance of this request .
func (server *GreeterServer) Greeter(ctx context.Context, request *greeter.GreeterRequest) (*greeter.GreeterResponse, error) {
rkgrpcctx.GetLogger(ctx).Info("Received request")
return &greeter.GreeterResponse{
Message: fmt.Sprintf("Hello %s!", request.Name),
}, nil
}The log was printed out !
2021-07-09T23:50:39.318+0800 INFO basic/main.go:36 Received request {"requestId": "c33698f2-3071-48d4-9d92-b1aa311e6c06"}modify Event
The log interceptor will RPC Request to create a Event example .
Users can add pairs,counters,errors.
adopt rkgrpcctx.GetEvent(ctx) Get this RPC Of Event example .
func (server *GreeterServer) Greeter(ctx context.Context, request *greeter.GreeterRequest) (*greeter.GreeterResponse, error) {
event := rkgrpcctx.GetEvent(ctx)
event.AddPair("key", "value")
return &greeter.GreeterResponse{
Message: fmt.Sprintf("Hello %s!", request.Name),
}, nil
}Event It's added pairs={"key":"value"}!
------------------------------------------------------------------------
endTime=2021-07-09T23:52:39.103351+08:00
startTime=2021-07-09T23:52:39.10332+08:00
elapsedNano=31154
timezone=CST
ids={"eventId":"92001951-80c1-4dda-8f14-f920834f5c61","requestId":"92001951-80c1-4dda-8f14-f920834f5c61"}
app={"appName":"rk-demo","appVersion":"master-f414049","entryName":"greeter","entryType":"GrpcEntry"}
env={"arch":"amd64","az":"*","domain":"*","hostname":"lark.local","localIP":"10.8.0.2","os":"darwin","realm":"*","region":"*"}
payloads={"grpcMethod":"Greeter","grpcService":"api.v1.Greeter","grpcType":"unaryServer","gwMethod":"","gwPath":"","gwScheme":"","gwUserAgent":""}
error={}
counters={}
pairs={"key":"value"}
timing={}
remoteAddr=localhost:58269
operation=/api.v1.Greeter/Greeter
resCode=OK
eventStatus=Ended
EOE边栏推荐
- Tstor onecos, focusing on a large number of object scenes
- Windowsvpn client is coveted by vulnerabilities, 53% of companies face supply chain attacks | global network security hotspot
- How to access the cloud game management server? Which cloud game management server can I choose?
- Ner's past, present and future Overview - past
- Shopee Clickhouse cold and hot data separation storage architecture and Practice
- 2022-2028 global third-party data platform industry research and trend analysis report
- What is an edge calculator? How is the unit price of the edge calculator calculated?
- What are the configuration requirements for cloud desktop servers? What are the main characteristics of the three points?
- What is the principle of intelligent image recognition? What are the applications of intelligent image recognition?
- Use Charles to capture the package of the applet through the mobile agent
猜你喜欢

2022-2028 global aircraft audio control panel system industry research and trend analysis report

2022-2028 global anti counterfeiting label industry research and trend analysis report

2022-2028 global aircraft wireless intercom system industry research and trend analysis report

2022-2028 global high tibial osteotomy plate industry research and trend analysis report

On Sunday, I rolled up the uni app "uview excellent UI framework"

The cost of on-site development of software talent outsourcing is higher than that of software project outsourcing. Why

2022-2028 global cell-based seafood industry research and trend analysis report

2022-2028 global genome editing mutation detection kit industry survey and trend analysis report
![[51nod] 3047 displacement operation](/img/cb/9380337adbc09c54a5b984cab7d3b8.jpg)
[51nod] 3047 displacement operation
![[summary of interview questions] zj5](/img/d8/ece82f8b2479adb948ba706f6f5039.jpg)
[summary of interview questions] zj5
随机推荐
Tencent Mu Lei: real scene 3D linking industrial Internet and consumer Internet
take the crown! Tencent security won the 2021 national network security week outstanding innovation achievement award
Get to know MySQL database
Is the cloud desktop server highly required for installation and configuration? Is cloud desktop easy to use?
What is the difference between elasticity and scalability of cloud computing? What does elastic scaling of cloud computing mean?
What port does the fortress machine use? What is the role of the fortress machine?
How to install CentOS 6.5 PHP extension
Why should I change my PC to a cloud desktop server? What are the characteristics of this server?
Highlights of future cloud native CIF Forum
How to access the cloud game management server? Which cloud game management server can I choose?
What is the edge calculator force? What about the edge calculator?
Velocitytracker use
Process kill problem
2022-2028 global high tibial osteotomy plate industry research and trend analysis report
Ner's past, present and future Overview - past
EIP maximum EIP EIP remote desktop access
What is the role of the distributed configuration center? What are the advantages of a distributed configuration center?
What is the use of cloud desktop security server configuration? What should I do?
How does cloud computing achieve elastic scaling? What are the characteristics of elasticity?
Clickhouse optimize table comprehensive analysis