diff --git a/v2/attrs.go b/v2/attrs.go index 8b9f34e..89d518e 100644 --- a/v2/attrs.go +++ b/v2/attrs.go @@ -14,11 +14,29 @@ func Hex(key string, value []byte) slog.Attr { // Hex6 is a convenience function for hex-encoded log attributes which prints // a maximum of 6 bytes. func Hex6(key string, value []byte) slog.Attr { - if len(value) <= 6 { + return HexN(key, value, 6) +} + +// Hex3 is a convenience function for hex-encoded log attributes which prints +// a maximum of 3 bytes. +func Hex3(key string, value []byte) slog.Attr { + return HexN(key, value, 3) +} + +// Hex2 is a convenience function for hex-encoded log attributes which prints +// a maximum of 2 bytes. +func Hex2(key string, value []byte) slog.Attr { + return HexN(key, value, 2) +} + +// HexN is a convenience function for hex-encoded log attributes which prints +// a maximum of n bytes. +func HexN(key string, value []byte, n uint) slog.Attr { + if len(value) <= int(n) { return slog.String(key, hex.EncodeToString(value)) } - return slog.String(key, hex.EncodeToString(value[:6])) + return slog.String(key, hex.EncodeToString(value[:n])) } // Fmt returns a slog.Attr with the formatted message which is only computed diff --git a/v2/handler_test.go b/v2/handler_test.go index 51553d9..3c6f7ff 100644 --- a/v2/handler_test.go +++ b/v2/handler_test.go @@ -139,6 +139,7 @@ var tests = []struct { log.InfoS(ctx, "Multi word string value", "key with spaces", "value") log.InfoS(ctx, "Number attribute", "key", 5) log.InfoS(ctx, "Bad key", "key") + log.InfoS(ctx, "Log with new line", "key", "value\nvalue") type b struct { name string @@ -160,6 +161,8 @@ var tests = []struct { [INF]: Multi word string value "key with spaces"=value [INF]: Number attribute key=5 [INF]: Bad key !BADKEY=key +[INF]: Log with new line key=value +value [INF]: Nil pointer value key= [INF]: Struct values key="&{name:Bob age:5 address:}" [INF]: Test context attributes request_id=5 user_name=alice key=value diff --git a/v2/utils.go b/v2/utils.go index da06b0b..5db9028 100644 --- a/v2/utils.go +++ b/v2/utils.go @@ -94,6 +94,9 @@ func needsQuoting(s string) bool { if len(s) == 0 { return true } + if strings.ContainsRune(s, '\n') { + return false + } for i := 0; i < len(s); { b := s[i] if b < utf8.RuneSelf {