How to get gRPC request when a panic occurs in Golang

huangapple go评论94阅读模式
英文:

How to get gRPC request when a panic occurs in Golang

问题

我在proto文件中定义了一个Go服务器,如下所示:

syntax = "proto3";

package go-package;

option go_package = "github.com/path/to/go-package";

import "vibe.proto";

service MyService {
  rpc Function (stream TheRequest) returns (stream TheResponse) {}
}

message TheRequest {
  oneof Payload {
    Config config = 1;
    Messages messages = 2;
  }
}

message Config {
  // 在这里配置一些字段
}

message Messages {
  repeated string messages = 1;
}

我正在使用https://github.com/grpc-ecosystem/go-grpc-middleware作为拦截器引擎。当发生panic时,我需要实现对请求或Messages的日志记录,因为当前代码发生panic时,我没有任何关于请求的信息。

英文:

I have a Go server defined like this in proto file:

syntax = "proto3";

package go-package;

option go_package = "github.com/path/to/go-package";

import "vibe.proto";

service MyService {
  rpc Function (stream TheRequest) returns (stream TheResponse) {}
}

message TheRequest {
  oneof Payload {
    Config config = 1;
    Messages messages = 2;
  }
}

message Config {
  // config some fields here
}

message Messages {
  repeated string messages = 1;
}

I'm using https://github.com/grpc-ecosystem/go-grpc-middleware as an interceptor engine. I need to implement logging of the request or Messages when I have a panic, because right now the code is panicked, but i don't have any information about the request.

答案1

得分: 3

只需添加带有恢复功能的拦截器,以下是一个简单的示例:

func RecoveryUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = status.Error(codes.Internal, fmt.Sprintf("Panic: `%s` %s", info.FullMethod, string(debug.Stack())))
		}
	}()
	return handler(ctx, req)
}
英文:

Just add interceptor with recovery, simple example:

func RecoveryUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = status.Error(codes.Internal, fmt.Sprintf("Panic: `%s` %s", info.FullMethod, string(debug.Stack())))
		}
	}()
	return handler(ctx, req)
}

huangapple
  • 本文由 发表于 2023年2月3日 08:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75330178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定