Skip to content

Commit

Permalink
Add docker-compose handler
Browse files Browse the repository at this point in the history
This handler filters out the docker-compose prefix, and then passes on
the rest of the line to another handler.
  • Loading branch information
bouk authored and Antoine Grondin committed Feb 18, 2020
1 parent 1c9bb30 commit 1568415
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
23 changes: 23 additions & 0 deletions docker_compose_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package humanlog

import (
"regexp"
)

// dcLogsPrefixRe parses out a prefix like 'web_1 | ' from docker-compose
var dcLogsPrefixRe = regexp.MustCompile("^(?:\x1b\\[\\d+m)?([a-zA-Z0-9._-]+)\\s+\\|(?:\x1b\\[0m)? (.*)$")

type handler interface {
TryHandle([]byte) bool
setField(key, val []byte)
}

func tryDockerComposePrefix(d []byte, nextHandler handler) bool {
if matches := dcLogsPrefixRe.FindSubmatch(d); matches != nil {
if nextHandler.TryHandle(matches[2]) {
nextHandler.setField([]byte(`service`), matches[1])
return true
}
}
return false
}
6 changes: 6 additions & 0 deletions json_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ func (h *JSONHandler) UnmarshalJSON(data []byte) bool {

return true
}
func (h *JSONHandler) setField(key, val []byte) {
if h.Fields == nil {
h.Fields = make(map[string]string)
}
h.Fields[string(key)] = string(val)
}

// Prettify the output in a logrus like fashion.
func (h *JSONHandler) Prettify(skipUnchanged bool) []byte {
Expand Down
8 changes: 8 additions & 0 deletions scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ func Scanner(src io.Reader, dst io.Writer, opts *HandlerOptions) error {
dst.Write(logfmtEntry.Prettify(opts.SkipUnchanged && lastLogfmt))
lastLogfmt = true

case tryDockerComposePrefix(lineData, &jsonEntry):
dst.Write(jsonEntry.Prettify(opts.SkipUnchanged && lastJSON))
lastJSON = true

case tryDockerComposePrefix(lineData, &logfmtEntry):
dst.Write(logfmtEntry.Prettify(opts.SkipUnchanged && lastLogfmt))
lastLogfmt = true

default:
lastLogfmt = false
lastJSON = false
Expand Down

0 comments on commit 1568415

Please sign in to comment.