Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

truncate bytes in proto logs #488

Merged
merged 2 commits into from
Oct 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions logger/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package logger

import (
"encoding/base64"
"fmt"
"strconv"

"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -106,7 +107,7 @@ func (p protoListMarshaller) MarshalLogArray(e zapcore.ArrayEncoder) error {
case protoreflect.StringKind:
e.AppendString(v.String())
case protoreflect.BytesKind:
e.AppendString(base64.RawStdEncoding.EncodeToString(v.Bytes()))
e.AppendString(marshalProtoBytes(v.Bytes()))
case protoreflect.MessageKind:
e.AppendObject(protoMarshaller{v.Message()})
}
Expand Down Expand Up @@ -142,11 +143,31 @@ func marshalProtoField(k string, f protoreflect.FieldDescriptor, v protoreflect.
}
case protoreflect.BytesKind:
if b := v.Bytes(); len(b) != 0 {
e.AddString(k, base64.RawStdEncoding.EncodeToString(b))
e.AddString(k, marshalProtoBytes(b))
}
case protoreflect.MessageKind:
if m := v.Message(); m.IsValid() {
e.AddObject(k, protoMarshaller{m})
}
}
}

func marshalProtoBytes(b []byte) string {
n := len(b)
if n > 64 {
b = b[:64]
}
s := base64.RawStdEncoding.EncodeToString(b)
switch {
case n <= 64:
return s
case n < 1<<10:
return fmt.Sprintf("%s... (%dbytes)", s, n)
case n < 1<<20:
return fmt.Sprintf("%s... (%.2fkB)", s, float64(n)/float64(1<<10))
case n < 1<<30:
return fmt.Sprintf("%s... (%.2fMB)", s, float64(n)/float64(1<<20))
default:
return fmt.Sprintf("%s... (%.2fGB)", s, float64(n)/float64(1<<30))
}
}
Loading