grpc-ecosystem / go-grpc-middleware

Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.
Apache License 2.0
6.29k stars 693 forks source link

Fix logging Example : log only first field, when using #693

Closed arckadious closed 9 months ago

arckadious commented 9 months ago

Changes

This PR follows issue #691.

Verification

grpc_logging.UnaryServerInterceptor(InterceptorLogrus(logger),grpc_logging.WithLogOnEvents(grpc_logging.FinishCall)),

My logging interceptor function :

func InterceptorLogrus(l log.FieldLogger) grpc_logging.Logger {
    return grpc_logging.LoggerFunc(func(_ context.Context, lvl grpc_logging.Level, msg string, fields ...any) {
        f := make(map[string]any, len(fields)/2)

        logFields := grpc_logging.Fields(fields)

        i := logFields.Iterator()

        for i.Next() {
            k, v := i.At()
            f[k] = v
        }
        l := l.WithFields(f)

        if _, ok := f["protocol"]; ok {
            l = l.WithField("system", f["protocol"])
        }
        l = l.WithField("span.kind", "server")

        switch lvl {
        case grpc_logging.LevelDebug:
            l.Debug(msg)
        case grpc_logging.LevelInfo:
            l.Info(msg)
        case grpc_logging.LevelWarn:
            l.Warn(msg)
        case grpc_logging.LevelError:
            l.Error(msg)
        default:
            l.Error(fmt.Sprintf("InterceptorLogrus : unknown level %v", lvl), " - logging message : ", msg)
        }
    })
}