当前位置:网站首页>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边栏推荐
- What is cloud desktop and how to connect to the server? What does the mainstream architecture of cloud desktop include?
- 2022-2028 global anti counterfeiting label industry research and trend analysis report
- What is edge computing? What are the characteristics of the Internet platform edge calculator?
- No monitoring information seen in kibana
- Why does the fortress machine use an application publisher? What are the main functions of the fortress machine
- 14. Tencent cloud IOT device side learning - data template application development
- Why can't cloud games connect to the server? What if the cloud game fails to connect to the server?
- Can elastic public IP be bound to a home server? The difference between elastic public IP and fixed IP
- What is the fortress machine? What role does the fortress machine play?
- Under what circumstances do you need a fortress machine? What are the functions of a fortress machine
猜你喜欢
![[51nod] 3047 displacement operation](/img/cb/9380337adbc09c54a5b984cab7d3b8.jpg)
[51nod] 3047 displacement operation

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

2022-2028 global aircraft wireless intercom system industry research and trend analysis report
![[51nod] 3395 n-bit gray code](/img/b5/2c072a11601de82cb92ade94672ecd.jpg)
[51nod] 3395 n-bit gray code

UI automation based on Selenium

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

2022-2028 global portable two-way radio equipment industry research and trend analysis report

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

Community pycharm installation visual database

On Sunday, I rolled up the uni app "uview excellent UI framework"
随机推荐
RI Geng series: tricks of using function pointers
[see you] on October 24, we met at Tencent Binhai building
How to set up a cloud desktop server? Is there a charge for cloud desktop server setup?
Go program lifecycle
What aspects does the intelligent identification system include? Is the technology of intelligent identification system mature now?
11111dasfada and I grew the problem hot hot I hot vasser shares
Ner's past, present and future Overview - past
How much is a fortress machine? Why do you need a fortress machine?
Grpc: implement service end flow restriction
What protocols do fortress computers have and what protocols do fortress computers generally use
What protocol does FTP belong to in Fortress machine and how to use FTP in Fortress machine
Concise and practical time code
Understanding Devops from the perspective of decision makers
Big coffee face to face | Dr. Chen Guoguo talks about intelligent voice
What is elastic scaling in cloud computing? What are the main applications of elastic scaling in cloud computing?
What is an edge calculator? How is the unit price of the edge calculator calculated?
How to access the cloud game management server? Which cloud game management server can I choose?
System library golang Org/x/time/rate frequency limiter bug
The medical technology giant was blackmailed and Microsoft announced 74 security vulnerabilities | global network security hotspot
2022-2028 global high tibial osteotomy plate industry research and trend analysis report