Skip to content

Commit

Permalink
assume we receive logs by lines and don't ignore those without EOL
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
  • Loading branch information
ndeloof committed Jun 7, 2023
1 parent e21a8d6 commit 4bf2fe9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 13 deletions.
6 changes: 3 additions & 3 deletions pkg/compose/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ func TestComposeService_Logs_Demux(t *testing.T) {
c1Stdout := stdcopy.NewStdWriter(c1Writer, stdcopy.Stdout)
c1Stderr := stdcopy.NewStdWriter(c1Writer, stdcopy.Stderr)
go func() {
_, err := c1Stdout.Write([]byte("hello stdout\n"))
_, err := c1Stdout.Write([]byte("hello\n stdout"))
assert.NoError(t, err, "Writing to fake stdout")
_, err = c1Stderr.Write([]byte("hello stderr\n"))
_, err = c1Stderr.Write([]byte("hello\n stderr"))
assert.NoError(t, err, "Writing to fake stderr")
_ = c1Writer.Close()
}()
Expand All @@ -94,7 +94,7 @@ func TestComposeService_Logs_Demux(t *testing.T) {

require.Equal(
t,
[]string{"hello stdout", "hello stderr"},
[]string{"hello", " stdout", "hello", " stderr"},
consumer.LogsForContainer("c"),
)
}
Expand Down
12 changes: 9 additions & 3 deletions pkg/utils/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,17 @@ func (s *splitWriter) Write(b []byte) (int, error) {
for {
b = s.buffer.Bytes()
index := bytes.Index(b, []byte{'\n'})
if index < 0 {
if index > 0 {
line := s.buffer.Next(index + 1)
s.consumer(string(line[:len(line)-1]))
} else {
line := s.buffer.String()
s.buffer.Reset()
if len(line) > 0 {
s.consumer(line)
}
break
}
line := s.buffer.Next(index + 1)
s.consumer(string(line[:len(line)-1]))
}
return n, nil
}
Expand Down
22 changes: 15 additions & 7 deletions pkg/utils/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,21 @@ func TestSplitWriter(t *testing.T) {
w := GetWriter(func(line string) {
lines = append(lines, line)
})
w.Write([]byte("h"))
w.Write([]byte("e"))
w.Write([]byte("l"))
w.Write([]byte("l"))
w.Write([]byte("o"))
w.Write([]byte("\n"))
w.Write([]byte("world!\n"))
w.Write([]byte("hello\n"))
w.Write([]byte("world\n"))
w.Write([]byte("!"))
assert.DeepEqual(t, lines, []string{"hello", "world", "!"})

}

//nolint:errcheck
func TestSplitWriterNoEOL(t *testing.T) {
var lines []string
w := GetWriter(func(line string) {
lines = append(lines, line)
})
w.Write([]byte("hello\n"))
w.Write([]byte("world!"))
assert.DeepEqual(t, lines, []string{"hello", "world!"})

}

0 comments on commit 4bf2fe9

Please sign in to comment.