Skip to content

Commit

Permalink
rewrite uuidPrefix to not drop lines
Browse files Browse the repository at this point in the history
  • Loading branch information
foosinn committed Oct 16, 2020
1 parent ed5a697 commit e319cc9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 35 deletions.
57 changes: 37 additions & 20 deletions helpers.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,53 @@
package main

import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strings"
"time"

"github.com/robfig/cron"
"golang.org/x/sync/errgroup"
"github.com/rs/xid"
)

func uuidPrefix(dest io.Writer, errGrp *errgroup.Group, uuid []byte) io.WriteCloser {
out, in := io.Pipe()
s := bufio.NewScanner(out)
errGrp.Go(func() (err error) {
for s.Scan() {
line := s.Bytes()
log := make([]byte, len(uuid)+len(line)+2)
pos := 0
for _, b := range [][]byte{uuid, []byte(" "), line, []byte("\n")} {
pos += copy(log[pos:], b)
}
_, err = dest.Write(log)
if err != nil {
return err
}
// uuidPrefixer is a io.Writer that prefixes every line with UUID
type uuidPrefixer struct {
uuid []byte
writer io.Writer
buf *bytes.Buffer
lastIsNewline bool
}

// newUUIDPrefixer generates a new uuidPrefixer with an UUID
func newUUIDPrefixer(dest io.Writer) *uuidPrefixer {
return &uuidPrefixer{
uuid: []byte(xid.New().String() + " "),
writer: dest,
buf: bytes.NewBuffer(nil),
lastIsNewline: true,
}
}

// Write satisfies golang io.Writer
func (prefixer *uuidPrefixer) Write(p []byte) (int, error) {
prefixer.buf.Reset()
for _, b := range p {
if prefixer.lastIsNewline {
prefixer.buf.Write(prefixer.uuid)
prefixer.lastIsNewline = false
}
prefixer.buf.WriteByte(b)
if b == '\n' {
prefixer.lastIsNewline = true
}
return
})
return in
}
n, err := prefixer.writer.Write(prefixer.buf.Bytes())
if n > len(p) {
n = len(p)
}
return n, err
}

func isQuiet(cr *CmdRequest) (bool, error) {
Expand Down
17 changes: 2 additions & 15 deletions middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"time"

"github.com/getsentry/sentry-go"
"github.com/rs/xid"
"golang.org/x/sync/errgroup"
)

Expand Down Expand Up @@ -67,25 +66,13 @@ func writeSyslog(g GuardFunc) GuardFunc {

// insertUUID prefixes each line with a uuid unless errfile-no-uuid flag is set
func insertUUID(g GuardFunc) GuardFunc {
errGrp := errgroup.Group{}
UUID := []byte(xid.New().String())
return func(ctx context.Context, cr *CmdRequest) (err error) {
if cr.ErrFileHideUUID {
return g(ctx, cr)
}
combined := uuidPrefix(cr.Status.Combined, &errGrp, UUID)
combined := newUUIDPrefixer(cr.Status.Combined)
cr.Status.Combined = combined
if err = g(ctx, cr); err != nil {
_ = combined.Close()
return err
}
if err = combined.Close(); err != nil {
return err
}
if err = errGrp.Wait(); err != nil {
return err
}
return combined.Close()
return g(ctx, cr)
}
}

Expand Down

0 comments on commit e319cc9

Please sign in to comment.