github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/docker/logger/formatter.go (about) 1 /* 2 Copyright 2021 The Skaffold Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package logger 18 19 import ( 20 "fmt" 21 "io" 22 "sync" 23 24 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker/tracker" 25 eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" 26 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" 27 ) 28 29 type DockerLogFormatter struct { 30 colorPicker output.ColorPicker 31 tracker *tracker.ContainerTracker 32 lock sync.Mutex 33 isMuted func() bool 34 id string 35 containerName string 36 prefix string 37 } 38 39 func NewDockerLogFormatter(colorPicker output.ColorPicker, tracker *tracker.ContainerTracker, isMuted func() bool, id string) *DockerLogFormatter { 40 return &DockerLogFormatter{ 41 colorPicker: colorPicker, 42 tracker: tracker, 43 isMuted: isMuted, 44 id: id, 45 containerName: tracker.ArtifactForContainer(id).ImageName, 46 prefix: prefix(tracker.ArtifactForContainer(id).ImageName), 47 } 48 } 49 50 func (d *DockerLogFormatter) Name() string { return d.prefix } 51 52 func (d *DockerLogFormatter) PrintLine(out io.Writer, line string) { 53 if d.isMuted() { 54 return 55 } 56 d.lock.Lock() 57 defer d.lock.Unlock() 58 59 formattedPrefix := d.prefix 60 // if our original prefix wasn't empty, append a space to the line 61 if d.prefix != "" { 62 formattedPrefix = fmt.Sprintf("%s ", formattedPrefix) 63 } 64 if output.IsColorable(out) { 65 formattedPrefix = d.color().Sprintf("%s", formattedPrefix) 66 } 67 formattedLine := fmt.Sprintf("%s%s", formattedPrefix, line) 68 eventV2.ApplicationLog("", d.containerName, formattedPrefix, line, formattedLine) 69 fmt.Fprint(out, formattedLine) 70 } 71 72 func (d *DockerLogFormatter) color() output.Color { 73 return d.colorPicker.Pick(d.tracker.ArtifactForContainer(d.id).Tag) 74 } 75 76 func prefix(containerName string) string { 77 if containerName == "" { // should only happen in testing 78 return "" 79 } 80 return fmt.Sprintf("[%s]", containerName) 81 }