2018-05-01 23:45:06 +00:00
|
|
|
// Package logtransport provides a transport that logs all of its messages.
|
|
|
|
package tunnelrpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2019-01-10 20:55:44 +00:00
|
|
|
"context"
|
2018-05-01 23:45:06 +00:00
|
|
|
|
2020-11-25 06:55:13 +00:00
|
|
|
"github.com/rs/zerolog"
|
2018-05-01 23:45:06 +00:00
|
|
|
"zombiezen.com/go/capnproto2/encoding/text"
|
|
|
|
"zombiezen.com/go/capnproto2/rpc"
|
|
|
|
rpccapnp "zombiezen.com/go/capnproto2/std/capnp/rpc"
|
|
|
|
)
|
|
|
|
|
|
|
|
type transport struct {
|
|
|
|
rpc.Transport
|
2020-11-25 06:55:13 +00:00
|
|
|
log *zerolog.Logger
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
|
2020-04-29 20:51:32 +00:00
|
|
|
// NewTransportLogger creates a new logger that proxies messages to and from t and
|
2020-11-25 06:55:13 +00:00
|
|
|
// logs them to log. If log is nil, then the log package's default
|
2018-05-01 23:45:06 +00:00
|
|
|
// logger is used.
|
2020-11-25 06:55:13 +00:00
|
|
|
func NewTransportLogger(log *zerolog.Logger, t rpc.Transport) rpc.Transport {
|
|
|
|
return &transport{Transport: t, log: log}
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *transport) SendMessage(ctx context.Context, msg rpccapnp.Message) error {
|
2023-04-19 17:52:25 +00:00
|
|
|
t.log.Trace().Msgf("rpc tx: %s", formatMsg(msg))
|
2018-05-01 23:45:06 +00:00
|
|
|
return t.Transport.SendMessage(ctx, msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *transport) RecvMessage(ctx context.Context) (rpccapnp.Message, error) {
|
|
|
|
msg, err := t.Transport.RecvMessage(ctx)
|
|
|
|
if err != nil {
|
2023-04-19 17:52:25 +00:00
|
|
|
t.log.Debug().Msgf("rpc rx error: %s", err)
|
2018-05-01 23:45:06 +00:00
|
|
|
return msg, err
|
|
|
|
}
|
2023-04-19 17:52:25 +00:00
|
|
|
t.log.Trace().Msgf("rpc rx: %s", formatMsg(msg))
|
2018-05-01 23:45:06 +00:00
|
|
|
return msg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func formatMsg(m rpccapnp.Message) string {
|
|
|
|
var buf bytes.Buffer
|
2020-11-25 06:55:13 +00:00
|
|
|
_ = text.NewEncoder(&buf).Encode(0x91b79f1f808db032, m.Struct)
|
2018-05-01 23:45:06 +00:00
|
|
|
return buf.String()
|
|
|
|
}
|