github.com/cpuid/libcompose@v0.4.0/cli/logger/color_logger.go (about) 1 package logger 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "strconv" 8 9 "github.com/docker/libcompose/logger" 10 "golang.org/x/crypto/ssh/terminal" 11 ) 12 13 // ColorLoggerFactory implements logger.Factory interface using ColorLogger. 14 type ColorLoggerFactory struct { 15 maxLength int 16 tty bool 17 } 18 19 // ColorLogger implements logger.Logger interface with color support. 20 type ColorLogger struct { 21 name string 22 colorPrefix string 23 factory *ColorLoggerFactory 24 } 25 26 // NewColorLoggerFactory creates a new ColorLoggerFactory. 27 func NewColorLoggerFactory() *ColorLoggerFactory { 28 return &ColorLoggerFactory{ 29 tty: terminal.IsTerminal(int(os.Stdout.Fd())), 30 } 31 } 32 33 // CreateContainerLogger implements logger.Factory.CreateContainerLogger. 34 func (c *ColorLoggerFactory) CreateContainerLogger(name string) logger.Logger { 35 return c.create(name) 36 } 37 38 // CreateBuildLogger implements logger.Factory.CreateBuildLogger. 39 func (c *ColorLoggerFactory) CreateBuildLogger(name string) logger.Logger { 40 return &logger.RawLogger{} 41 } 42 43 // CreatePullLogger implements logger.Factory.CreatePullLogger. 44 func (c *ColorLoggerFactory) CreatePullLogger(name string) logger.Logger { 45 return &logger.NullLogger{} 46 } 47 48 // CreateBuildLogger implements logger.Factory.CreateContainerLogger. 49 func (c *ColorLoggerFactory) create(name string) logger.Logger { 50 if c.maxLength < len(name) { 51 c.maxLength = len(name) 52 } 53 54 return &ColorLogger{ 55 name: name, 56 factory: c, 57 colorPrefix: <-colorPrefix, 58 } 59 } 60 61 // Out implements logger.Logger.Out. 62 func (c *ColorLogger) Out(bytes []byte) { 63 if len(bytes) == 0 { 64 return 65 } 66 logFmt, name := c.getLogFmt() 67 message := fmt.Sprintf(logFmt, name, string(bytes)) 68 fmt.Print(message) 69 } 70 71 // Err implements logger.Logger.Err. 72 func (c *ColorLogger) Err(bytes []byte) { 73 if len(bytes) == 0 { 74 return 75 } 76 logFmt, name := c.getLogFmt() 77 message := fmt.Sprintf(logFmt, name, string(bytes)) 78 fmt.Fprint(os.Stderr, message) 79 } 80 81 // OutWriter returns the base writer 82 func (c *ColorLogger) OutWriter() io.Writer { 83 return os.Stdout 84 } 85 86 // ErrWriter returns the base writer 87 func (c *ColorLogger) ErrWriter() io.Writer { 88 return os.Stderr 89 } 90 91 func (c *ColorLogger) getLogFmt() (string, string) { 92 pad := c.factory.maxLength 93 94 logFmt := "%s | %s" 95 if c.factory.tty { 96 logFmt = c.colorPrefix + " %s" 97 } 98 99 name := fmt.Sprintf("%-"+strconv.Itoa(pad)+"s", c.name) 100 101 return logFmt, name 102 }