Skip to content

Commit

Permalink
rpc: truncate call error data logs (#30028)
Browse files Browse the repository at this point in the history
Co-authored-by: Felix Lange <[email protected]>
  • Loading branch information
ceyonur and fjl authored Jun 28, 2024
1 parent 06f1d07 commit 7cfff30
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions rpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
package rpc

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -468,16 +471,16 @@ func (h *handler) handleCallMsg(ctx *callProc, msg *jsonrpcMessage) *jsonrpcMess

case msg.isCall():
resp := h.handleCall(ctx, msg)
var ctx []interface{}
ctx = append(ctx, "reqid", idForLog{msg.ID}, "duration", time.Since(start))
var logctx []any
logctx = append(logctx, "reqid", idForLog{msg.ID}, "duration", time.Since(start))
if resp.Error != nil {
ctx = append(ctx, "err", resp.Error.Message)
logctx = append(logctx, "err", resp.Error.Message)
if resp.Error.Data != nil {
ctx = append(ctx, "errdata", resp.Error.Data)
logctx = append(logctx, "errdata", formatErrorData(resp.Error.Data))
}
h.log.Warn("Served "+msg.Method, ctx...)
h.log.Warn("Served "+msg.Method, logctx...)
} else {
h.log.Debug("Served "+msg.Method, ctx...)
h.log.Debug("Served "+msg.Method, logctx...)
}
return resp

Expand Down Expand Up @@ -591,3 +594,33 @@ func (id idForLog) String() string {
}
return string(id.RawMessage)
}

var errTruncatedOutput = errors.New("truncated output")

type limitedBuffer struct {
output []byte
limit int
}

func (buf *limitedBuffer) Write(data []byte) (int, error) {
avail := max(buf.limit, len(buf.output))
if len(data) < avail {
buf.output = append(buf.output, data...)
return len(data), nil
}
buf.output = append(buf.output, data[:avail]...)
return avail, errTruncatedOutput
}

func formatErrorData(v any) string {
buf := limitedBuffer{limit: 1024}
err := json.NewEncoder(&buf).Encode(v)
switch {
case err == nil:
return string(bytes.TrimRight(buf.output, "\n"))
case errors.Is(err, errTruncatedOutput):
return fmt.Sprintf("%s... (truncated)", buf.output)
default:
return fmt.Sprintf("bad error data (err=%v)", err)
}
}

0 comments on commit 7cfff30

Please sign in to comment.