Skip to content

Commit 0f4e86e

Browse files
committed
Add a CustomString type to allow unescaped output.
When trying to print multi-line (or otherwise formatted) messages, the fact that all strings are escaped becomes a problem. For example: ``` func PanicLog() { if err := recover(); err != nil { log.Crit("Panic", "stack", string(debug.Stack())) } } ``` The stack trace becomes a single line, with all \n's and \t's escaped. With this new type, the central line becomes: ``` log.Crit("Panic", "stack", log.CustomString(debug.Stack())) ``` and now it formats in a readable way. CustomString multi-line values are rendered with a leading `> `, to enable machine parsing. An example output is viewable here: https://gist.github.com/kormat/10e09e4dcfef0115c65fcdc20c98297e
1 parent 67afb5e commit 0f4e86e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Diff for: format.go

+21
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,27 @@ const (
1616
termTimeFormat = "01-02|15:04:05"
1717
floatFormat = 'f'
1818
termMsgJust = 40
19+
customPrefix = "> "
1920
)
2021

22+
// CustomString is rendered without escaping of newlines/tabs/etc.
23+
type CustomString string
24+
25+
func (c CustomString) Render() string {
26+
var buf bytes.Buffer
27+
lines := strings.Split(string(c), "\n")
28+
buf.WriteByte('\n')
29+
for i, line := range lines {
30+
if i == len(lines)-1 && line == "" {
31+
break
32+
}
33+
buf.WriteString(customPrefix)
34+
buf.WriteString(line)
35+
buf.WriteByte('\n')
36+
}
37+
return buf.String()
38+
}
39+
2140
// Format is the interface implemented by StreamHandler formatters.
2241
type Format interface {
2342
Format(r *Record) []byte
@@ -228,6 +247,8 @@ func formatLogfmtValue(value interface{}) string {
228247
return strconv.FormatFloat(v, floatFormat, 3, 64)
229248
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
230249
return fmt.Sprintf("%d", value)
250+
case CustomString:
251+
return v.Render()
231252
case string:
232253
return escapeString(v)
233254
default:

0 commit comments

Comments
 (0)