cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
tunnelrpc/logtransport.go
45lines · modecode
| 1 | // Package logtransport provides a transport that logs all of its messages. |
| 2 | package tunnelrpc |
| 3 | |
| 4 | import ( |
| 5 | "bytes" |
| 6 | |
| 7 | log "github.com/sirupsen/logrus" |
| 8 | "golang.org/x/net/context" |
| 9 | "zombiezen.com/go/capnproto2/encoding/text" |
| 10 | "zombiezen.com/go/capnproto2/rpc" |
| 11 | rpccapnp "zombiezen.com/go/capnproto2/std/capnp/rpc" |
| 12 | ) |
| 13 | |
| 14 | type transport struct { |
| 15 | rpc.Transport |
| 16 | l *log.Entry |
| 17 | } |
| 18 | |
| 19 | // New creates a new logger that proxies messages to and from t and |
| 20 | // logs them to l. If l is nil, then the log package's default |
| 21 | // logger is used. |
| 22 | func NewTransportLogger(l *log.Entry, t rpc.Transport) rpc.Transport { |
| 23 | return &transport{Transport: t, l: l} |
| 24 | } |
| 25 | |
| 26 | func (t *transport) SendMessage(ctx context.Context, msg rpccapnp.Message) error { |
| 27 | t.l.Debugf("tx %s", formatMsg(msg)) |
| 28 | return t.Transport.SendMessage(ctx, msg) |
| 29 | } |
| 30 | |
| 31 | func (t *transport) RecvMessage(ctx context.Context) (rpccapnp.Message, error) { |
| 32 | msg, err := t.Transport.RecvMessage(ctx) |
| 33 | if err != nil { |
| 34 | t.l.WithError(err).Debug("rx error") |
| 35 | return msg, err |
| 36 | } |
| 37 | t.l.Debugf("rx %s", formatMsg(msg)) |
| 38 | return msg, nil |
| 39 | } |
| 40 | |
| 41 | func formatMsg(m rpccapnp.Message) string { |
| 42 | var buf bytes.Buffer |
| 43 | text.NewEncoder(&buf).Encode(0x91b79f1f808db032, m.Struct) |
| 44 | return buf.String() |
| 45 | } |
| 46 | |