Skip to content

Commit aa8e0d3

Browse files
authored
fix: special characters (#23)
1 parent 583b111 commit aa8e0d3

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

internal/pkg/source/entry.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package source
33
import (
44
"bytes"
55
"encoding/json"
6+
"strings"
7+
"unicode"
68

79
"github.com/charmbracelet/bubbles/table"
810
"github.com/valyala/fastjson"
@@ -79,15 +81,29 @@ func ParseLogEntry(line json.RawMessage) LogEntry {
7981
return LogEntry{
8082
Line: line,
8183
Time: "-",
82-
Message: string(line),
84+
Message: formatMessage(string(line)),
8385
Level: LevelUnknown,
8486
}
8587
}
8688

8789
return LogEntry{
8890
Line: line,
89-
Time: extractTime(value),
90-
Message: extractMessage(value),
91+
Time: formatMessage(extractTime(value)),
92+
Message: formatMessage(extractMessage(value)),
9193
Level: extractLevel(value),
9294
}
9395
}
96+
97+
func formatMessage(msg string) string {
98+
msg = strings.NewReplacer("\n", "\\n", "\t", "\\t").Replace(msg)
99+
100+
msg = strings.Map(func(r rune) rune {
101+
if unicode.IsPrint(r) {
102+
return r
103+
}
104+
105+
return -1
106+
}, msg)
107+
108+
return msg
109+
}

internal/pkg/source/entry_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,14 @@ func TestParseLogEntry(t *testing.T) {
7575

7676
assert.Equal(t, "msg", logEntry.Message)
7777
},
78+
}, {
79+
Name: "message_special_rune",
80+
JSON: `{"message":"mes` + string(rune(1)) + `sage"}`,
81+
Assert: func(tb testing.TB, logEntry source.LogEntry) {
82+
tb.Helper()
83+
84+
assert.Equal(t, "message", logEntry.Message)
85+
},
7886
}, {
7987
Name: "error",
8088
JSON: `{"error":"error"}`,

internal/pkg/source/helper.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
func extractTime(value *fastjson.Value) string {
1111
timeValue := extractValue(value, "timestamp", "time", "t")
1212
if timeValue != "" {
13-
return strings.TrimSpace(timeValue)
13+
return formatMessage(strings.TrimSpace(timeValue))
1414
}
1515

1616
return "-"
@@ -19,7 +19,7 @@ func extractTime(value *fastjson.Value) string {
1919
func extractLevel(value *fastjson.Value) Level {
2020
level := extractValue(value, "level", "lvl")
2121

22-
return ParseLevel(level)
22+
return ParseLevel(formatMessage(level))
2323
}
2424

2525
func extractValue(value *fastjson.Value, keys ...string) string {

0 commit comments

Comments
 (0)