Skip to content

Commit 1d79e84

Browse files
authored
Merge pull request #2086 from CortexFoundation/dev
rpc: truncate call error data logs
2 parents ba7d894 + 4ee015c commit 1d79e84

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"
@@ -418,16 +421,16 @@ func (h *handler) handleCallMsg(ctx *callProc, msg *jsonrpcMessage) *jsonrpcMess
418421
return nil
419422
case msg.isCall():
420423
resp := h.handleCall(ctx, msg)
421-
var ctx []any
422-
ctx = append(ctx, "reqid", idForLog{msg.ID}, "t", time.Since(start))
424+
var logctx []any
425+
logctx = append(logctx, "reqid", idForLog{msg.ID}, "duration", time.Since(start))
423426
if resp.Error != nil {
424-
ctx = append(ctx, "err", resp.Error.Message)
427+
logctx = append(logctx, "err", resp.Error.Message)
425428
if resp.Error.Data != nil {
426-
ctx = append(ctx, "errdata", resp.Error.Data)
429+
logctx = append(logctx, "errdata", formatErrorData(resp.Error.Data))
427430
}
428-
h.log.Warn("Served "+msg.Method, ctx...)
431+
h.log.Warn("Served "+msg.Method, logctx...)
429432
} else {
430-
h.log.Debug("Served "+msg.Method, ctx...)
433+
h.log.Debug("Served "+msg.Method, logctx...)
431434
}
432435
return resp
433436
case msg.hasValidID():
@@ -537,3 +540,33 @@ func (id idForLog) String() string {
537540
}
538541
return string(id.RawMessage)
539542
}
543+
544+
var errTruncatedOutput = errors.New("truncated output")
545+
546+
type limitedBuffer struct {
547+
output []byte
548+
limit int
549+
}
550+
551+
func (buf *limitedBuffer) Write(data []byte) (int, error) {
552+
avail := max(buf.limit, len(buf.output))
553+
if len(data) < avail {
554+
buf.output = append(buf.output, data...)
555+
return len(data), nil
556+
}
557+
buf.output = append(buf.output, data[:avail]...)
558+
return avail, errTruncatedOutput
559+
}
560+
561+
func formatErrorData(v any) string {
562+
buf := limitedBuffer{limit: 1024}
563+
err := json.NewEncoder(&buf).Encode(v)
564+
switch {
565+
case err == nil:
566+
return string(bytes.TrimRight(buf.output, "\n"))
567+
case errors.Is(err, errTruncatedOutput):
568+
return fmt.Sprintf("%s... (truncated)", buf.output)
569+
default:
570+
return fmt.Sprintf("bad error data (err=%v)", err)
571+
}
572+
}

0 commit comments

Comments
 (0)