当前位置:网站首页>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 .

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 interceptor

2. 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
EOE

Change 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 console

Modify 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 console

Concept

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
EOE

Log 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
原网站

版权声明
本文为[Trespass ]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211011044722246Q.html