Skip to content

Commit 7cfff30

Browse files
ceyonurfjl
andauthored
rpc: truncate call error data logs (#30028)
Co-authored-by: Felix Lange <[email protected]>
1 parent 06f1d07 commit 7cfff30

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

rpc/handler.go

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@
1717
package rpc
1818

1919
import (
20+
"bytes"
2021
"context"
2122
"encoding/json"
23+
"errors"
24+
"fmt"
2225
"reflect"
2326
"strconv"
2427
"strings"
@@ -468,16 +471,16 @@ func (h *handler) handleCallMsg(ctx *callProc, msg *jsonrpcMessage) *jsonrpcMess
468471

469472
case msg.isCall():
470473
resp := h.handleCall(ctx, msg)
471-
var ctx []interface{}
472-
ctx = append(ctx, "reqid", idForLog{msg.ID}, "duration", time.Since(start))
474+
var logctx []any
475+
logctx = append(logctx, "reqid", idForLog{msg.ID}, "duration", time.Since(start))
473476
if resp.Error != nil {
474-
ctx = append(ctx, "err", resp.Error.Message)
477+
logctx = append(logctx, "err", resp.Error.Message)
475478
if resp.Error.Data != nil {
476-
ctx = append(ctx, "errdata", resp.Error.Data)
479+
logctx = append(logctx, "errdata", formatErrorData(resp.Error.Data))
477480
}
478-
h.log.Warn("Served "+msg.Method, ctx...)
481+
h.log.Warn("Served "+msg.Method, logctx...)
479482
} else {
480-
h.log.Debug("Served "+msg.Method, ctx...)
483+
h.log.Debug("Served "+msg.Method, logctx...)
481484
}
482485
return resp
483486

@@ -591,3 +594,33 @@ func (id idForLog) String() string {
591594
}
592595
return string(id.RawMessage)
593596
}
597+
598+
var errTruncatedOutput = errors.New("truncated output")
599+
600+
type limitedBuffer struct {
601+
output []byte
602+
limit int
603+
}
604+
605+
func (buf *limitedBuffer) Write(data []byte) (int, error) {
606+
avail := max(buf.limit, len(buf.output))
607+
if len(data) < avail {
608+
buf.output = append(buf.output, data...)
609+
return len(data), nil
610+
}
611+
buf.output = append(buf.output, data[:avail]...)
612+
return avail, errTruncatedOutput
613+
}
614+
615+
func formatErrorData(v any) string {
616+
buf := limitedBuffer{limit: 1024}
617+
err := json.NewEncoder(&buf).Encode(v)
618+
switch {
619+
case err == nil:
620+
return string(bytes.TrimRight(buf.output, "\n"))
621+
case errors.Is(err, errTruncatedOutput):
622+
return fmt.Sprintf("%s... (truncated)", buf.output)
623+
default:
624+
return fmt.Sprintf("bad error data (err=%v)", err)
625+
}
626+
}

0 commit comments

Comments
 (0)