forked from docker/libcompose
/
color_logger.go
76 lines (63 loc) · 1.56 KB
/
color_logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package logger
import (
"fmt"
"os"
"strconv"
"github.com/docker/libcompose/logger"
"golang.org/x/crypto/ssh/terminal"
)
// ColorLoggerFactory implements logger.Factory interface using ColorLogger.
type ColorLoggerFactory struct {
maxLength int
tty bool
}
// ColorLogger implements logger.Logger interface with color support.
type ColorLogger struct {
name string
colorPrefix string
factory *ColorLoggerFactory
}
// NewColorLoggerFactory creates a new ColorLoggerFactory.
func NewColorLoggerFactory() *ColorLoggerFactory {
return &ColorLoggerFactory{
tty: terminal.IsTerminal(int(os.Stdout.Fd())),
}
}
// Create implements logger.Factory.Create.
func (c *ColorLoggerFactory) Create(name string) logger.Logger {
if c.maxLength < len(name) {
c.maxLength = len(name)
}
return &ColorLogger{
name: name,
factory: c,
colorPrefix: <-colorPrefix,
}
}
// Out implements logger.Logger.Out.
func (c *ColorLogger) Out(bytes []byte) {
if len(bytes) == 0 {
return
}
logFmt, name := c.getLogFmt()
message := fmt.Sprintf(logFmt, name, string(bytes))
fmt.Print(message)
}
// Err implements logger.Logger.Err.
func (c *ColorLogger) Err(bytes []byte) {
if len(bytes) == 0 {
return
}
logFmt, name := c.getLogFmt()
message := fmt.Sprintf(logFmt, name, string(bytes))
fmt.Fprint(os.Stderr, message)
}
func (c *ColorLogger) getLogFmt() (string, string) {
pad := c.factory.maxLength
logFmt := "%s | %s"
if c.factory.tty {
logFmt = c.colorPrefix + " %s"
}
name := fmt.Sprintf("%-"+strconv.Itoa(pad)+"s", c.name)
return logFmt, name
}