-
Notifications
You must be signed in to change notification settings - Fork 17
[ACI-4111] Add a log interceptor #283
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
1f61b73
Add a log interceptor
Badlazzor e7f0a9d
Close intercepted writer
Badlazzor ec9cdc3
Log writer and scanner errors to stderr
Badlazzor 19d4f3a
Update loginterceptor/loginterceptor.go
Badlazzor 878fd89
Fix regex
Badlazzor a915afc
Close pipe reader on coroutine end
Badlazzor 9e64079
Fix AI review suggestions
Badlazzor 62bff66
Remove pr close on run, Close() handles it
Badlazzor 0b980e1
Add test for interceptor and close chained writers on interceptor close
Badlazzor 368c1e6
Make closing optional for interceptor writers
Badlazzor 115dc40
Update variable names, introduce logger, update closing mechanism
Badlazzor 126f22c
Close reader too, restructure after goroutine closing
Badlazzor 5922f82
Remove superfuous writer close
Badlazzor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package loginterceptor | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "io" | ||
| "regexp" | ||
| "sync" | ||
|
|
||
| "github.com/bitrise-io/go-utils/v2/log" | ||
| ) | ||
|
|
||
| // PrefixInterceptor intercept writes: if a line begins with prefix, it will be written to | ||
| // both writers. Partial writes without newline are buffered until a newline. | ||
| type PrefixInterceptor struct { | ||
| prefixRegexp *regexp.Regexp | ||
| intercepted io.Writer | ||
| target io.Writer | ||
| logger log.Logger | ||
|
|
||
| // internal pipe and goroutine to scan and route | ||
| internalReader *io.PipeReader | ||
| internalWriter *io.PipeWriter | ||
|
|
||
| // close once | ||
| closeOnce sync.Once | ||
| closeErr error | ||
| } | ||
|
|
||
| // NewPrefixInterceptor returns an io.WriteCloser. Writes are based on line prefix. | ||
| func NewPrefixInterceptor(prefixRegexp *regexp.Regexp, intercepted, target io.Writer, logger log.Logger) *PrefixInterceptor { | ||
| pipeReader, pipeWriter := io.Pipe() | ||
| interceptor := &PrefixInterceptor{ | ||
| prefixRegexp: prefixRegexp, | ||
| intercepted: intercepted, | ||
| target: target, | ||
| logger: logger, | ||
| internalReader: pipeReader, | ||
| internalWriter: pipeWriter, | ||
| } | ||
| go interceptor.run() | ||
| return interceptor | ||
| } | ||
|
|
||
| // Write implements io.Writer. It writes into an internal pipe which the interceptor goroutine consumes. | ||
| func (i *PrefixInterceptor) Write(p []byte) (int, error) { | ||
Badlazzor marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return i.internalWriter.Write(p) | ||
| } | ||
|
|
||
| // Close stops the interceptor and closes the pipe. | ||
| func (i *PrefixInterceptor) Close() error { | ||
| i.closeOnce.Do(func() { | ||
| i.closeErr = i.internalWriter.Close() | ||
| }) | ||
| return i.closeErr | ||
| } | ||
|
|
||
| func (i *PrefixInterceptor) closeAfterRun() { | ||
| // Close writers if able | ||
| if interceptedCloser, ok := i.intercepted.(io.Closer); ok { | ||
Badlazzor marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err := interceptedCloser.Close(); err != nil { | ||
| i.logger.Errorf("closing intercepted writer: %v", err) | ||
| } | ||
| } | ||
| if originalCloser, ok := i.target.(io.Closer); ok { | ||
| if err := originalCloser.Close(); err != nil { | ||
| i.logger.Errorf("closing original writer: %v", err) | ||
| } | ||
| } | ||
|
|
||
| if err := i.internalReader.Close(); err != nil { | ||
| i.logger.Errorf("internal reader: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // run reads lines (and partial final chunk) and writes them. | ||
| func (i *PrefixInterceptor) run() { | ||
| defer i.closeAfterRun() | ||
|
|
||
| // Use a scanner but with a large buffer to handle long lines. | ||
| scanner := bufio.NewScanner(i.internalReader) | ||
| const maxTokenSize = 10 * 1024 * 1024 | ||
| buf := make([]byte, 0, 64*1024) | ||
| scanner.Buffer(buf, maxTokenSize) | ||
|
|
||
| for scanner.Scan() { | ||
| line := scanner.Text() // note: newline removed | ||
| // re-append newline to preserve same output format | ||
| outLine := line + "\n" | ||
|
|
||
| // Write to intercepted channel if matching regexp | ||
| if i.prefixRegexp.MatchString(line) { | ||
| if _, err := io.WriteString(i.intercepted, outLine); err != nil { | ||
| i.logger.Errorf("intercept writer error: %v", err) | ||
| } | ||
| } | ||
| // Always write to target channel | ||
| if _, err := io.WriteString(i.target, outLine); err != nil { | ||
| i.logger.Errorf("writer error: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // handle any scanner error | ||
| if err := scanner.Err(); err != nil { | ||
| i.logger.Errorf("router scanner error: %v\n", err) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| package loginterceptor_test | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "regexp" | ||
| "sync" | ||
| "testing" | ||
|
|
||
| "github.com/bitrise-io/go-utils/v2/log" | ||
| "github.com/bitrise-io/go-xcode/v2/loginterceptor" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestPrefixInterceptor(t *testing.T) { | ||
| interceptReader, interceptWriter := io.Pipe() | ||
| targetReader, targetWriter := io.Pipe() | ||
| re := regexp.MustCompile(`^\[Bitrise.*\].*`) | ||
|
|
||
| sut := loginterceptor.NewPrefixInterceptor(re, interceptWriter, targetWriter, log.NewLogger()) | ||
|
|
||
| msg1 := "Log message without prefix\n" | ||
| msg2 := "[Bitrise Analytics] Log message with prefix\n" | ||
| msg3 := "[Bitrise Build Cache] Log message with prefix\n" | ||
| msg4 := "Stuff [Bitrise Build Cache] Log message without prefix\n" | ||
|
|
||
| go func() { | ||
| //nolint:errCheck | ||
| defer sut.Close() | ||
|
|
||
| _, _ = sut.Write([]byte(msg1)) | ||
| _, _ = sut.Write([]byte(msg2)) | ||
| _, _ = sut.Write([]byte(msg3)) | ||
| _, _ = sut.Write([]byte(msg4)) | ||
| }() | ||
|
|
||
| intercepted, target, err := readTwo(interceptReader, targetReader) | ||
| assert.NoError(t, err) | ||
| assert.Equal(t, msg2+msg3, string(intercepted)) | ||
| assert.Equal(t, msg1+msg2+msg3+msg4, string(target)) | ||
| } | ||
|
|
||
| func readTwo(r1, r2 io.Reader) (out1, out2 []byte, err error) { | ||
| var ( | ||
| wg sync.WaitGroup | ||
| e1, e2 error | ||
| ) | ||
| wg.Add(2) | ||
|
|
||
| var b1, b2 bytes.Buffer | ||
|
|
||
| go func() { | ||
| defer wg.Done() | ||
| _, e1 = io.Copy(&b1, r1) | ||
| }() | ||
|
|
||
| go func() { | ||
| defer wg.Done() | ||
| _, e2 = io.Copy(&b2, r2) | ||
| }() | ||
|
|
||
| wg.Wait() | ||
|
|
||
| // prefer to return the first non-nil error | ||
| if e1 != nil { | ||
| return b1.Bytes(), b2.Bytes(), e1 | ||
| } | ||
| if e2 != nil { | ||
| return b1.Bytes(), b2.Bytes(), e2 | ||
| } | ||
| return b1.Bytes(), b2.Bytes(), nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.