如何使用Logrus实现gRPC负载JSON格式日志并输出proto定义的HTTP端点
解决方案
1. 调整Logrus输出格式为JSON
首先修改Logrus初始化配置,指定JSONFormatter即可实现结构化JSON输出:
import "github.com/sirupsen/logrus" logger := logrus.New() // 配置JSON格式 logger.SetFormatter(&logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05.000", PrettyPrint: false, // 生产环境可关闭,减少日志体积 }) // 可选:配置日志级别 logger.SetLevel(logrus.InfoLevel)
如果你需要最终示例中的行式自定义格式,可以参考最后一节的Formatter实现。
2. 把请求负载改为结构化对象
默认的gRPC日志中间件会把Proto消息序列化为Proto文本格式,导致grpc.request.content为转义字符串。你可以通过自定义消息序列化器解决:
import ( "encoding/json" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus" ) // 自定义消息序列化器,将Proto消息转为JSON结构 customMsgProducer := func(ctx context.Context, msg interface{}, fullMethod string) map[string]interface{} { protoMsg, ok := msg.(proto.Message) if !ok { return map[string]interface{}{"raw": msg} } // Proto转JSON字节 jsonBytes, err := protojson.Marshal(protoMsg) if err != nil { return map[string]interface{}{"marshal_error": err.Error(), "raw": msg} } // 转为map结构,Logrus会直接序列化为JSON对象 var reqObj map[string]interface{} if err := json.Unmarshal(jsonBytes, &reqObj); err != nil { return map[string]interface{}{"parse_error": err.Error(), "raw": string(jsonBytes)} } return reqObj } // 把自定义序列化器加入Option opts := []grpc_logrus.Option{ grpc_logrus.WithDurationField(func(duration time.Duration) (key string, value interface{}) { return "grpc.time_ns", duration.Nanoseconds() }), grpc_logrus.WithMessageProducer(customMsgProducer), // 新增这行 }
3. 提取Proto定义的HTTP端点到日志
你需要通过Proto反射读取方法的google.api.http扩展选项,逻辑如下:
首先导入相关依赖:
import ( "fmt" "strings" "google.golang.org/genproto/googleapis/api/annotations" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" )
实现获取HTTP端点的工具函数:
func getHttpInfo(fullMethod string, reqObj map[string]interface{}) (httpMethod string, fullPath string, err error) { // 解析全方法名,格式为 /{服务包名}.{服务名}/{方法名} parts := strings.Split(strings.TrimPrefix(fullMethod, "/"), "/") if len(parts) != 2 { return "", "", fmt.Errorf("invalid method name: %s", fullMethod) } serviceName, methodName := parts[0], parts[1] // 查找服务和方法的描述 svcDesc, err := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(serviceName)) if err != nil { return "", "", err } methodDesc := svcDesc.(protoreflect.ServiceDescriptor).Methods().ByName(protoreflect.Name(methodName)) if methodDesc == nil { return "", "", fmt.Errorf("method not found: %s", methodName) } // 读取HTTP扩展选项 httpRule := proto.GetExtension(methodDesc.Options(), annotations.E_Http).(*annotations.HttpRule) switch pattern := httpRule.GetPattern().(type) { case *annotations.HttpRule_Get: httpMethod = "GET" fullPath = pattern.Get case *annotations.HttpRule_Post: httpMethod = "POST" fullPath = pattern.Post // 按需补充PUT/DELETE/PATCH等其他方法的判断 } // 替换路径中的占位符,比如{bankId}替换为请求中对应的实际值 for k, v := range reqObj { placeholder := fmt.Sprintf("{%s}", k) strV := fmt.Sprintf("%v", v) fullPath = strings.ReplaceAll(fullPath, placeholder, strV) } return httpMethod, fullPath, nil }
然后把HTTP信息加到日志字段中,你可以在自定义的消息序列化器里调用上面的函数,把http.method、http.path加到返回的map里即可。
4. 自定义行式日志格式(可选)
如果你需要示例中逐行打印的日志格式,自定义Logrus的Formatter即可:
type CustomFYZFormatter struct{} func (f *CustomFYZFormatter) Format(entry *logrus.Entry) ([]byte, error) { ts := entry.Time.Format("2006-01-02 15:04:05.000") level := strings.ToUpper(entry.Level.String()[:1]) var lines []string if path, ok := entry.Data["http.path"]; ok { // 可自行拼接域名前缀到path前面 lines = append(lines, fmt.Sprintf("%s %s/FYZ: Request To: %s", ts, level, path)) } if method, ok := entry.Data["http.method_code"]; ok { lines = append(lines, fmt.Sprintf("%s %s/FYZ: Method: %v", ts, level, method)) } if req, ok := entry.Data["grpc.request.content"]; ok { reqJson, _ := json.Marshal(req) lines = append(lines, fmt.Sprintf("%s %s/FYZ: Request Parameter: %s", ts, level, string(reqJson))) } if len(lines) == 0 { lines = append(lines, fmt.Sprintf("%s %s/FYZ: %s", ts, level, entry.Message)) } return []byte(strings.Join(lines, "\n") + "\n"), nil } // 初始化时设置自定义Formatter logger.SetFormatter(&CustomFYZFormatter{})
内容的提问来源于stack exchange,提问作者Enryu
相关产品推荐
相关产品推荐

