-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
94 lines (80 loc) · 1.84 KB
/
logger.go
File metadata and controls
94 lines (80 loc) · 1.84 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"io"
"strings"
"time"
"github.com/rs/zerolog"
)
var (
Reset = "\033[0m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
Gray = "\033[37m"
White = "\033[97m"
Purple = "\033[35m"
Salmon = "\033[38;5;210m"
)
var Colors = []string{Green, Blue, Yellow, Red, Magenta, Cyan, Gray, White, Purple, Salmon}
type Config struct {
Output io.Writer
ContainerName string
Color string
}
func NewLogWriter(cfg Config, stream string) *LogWriter {
output := zerolog.ConsoleWriter{Out: cfg.Output, NoColor: false}
output.FormatMessage = func(i interface{}) string {
return fmt.Sprintf("%s ", i)
}
output.FormatTimestamp = func(i interface{}) string {
return fmt.Sprintf("%s |", i)
}
output.TimeFormat = time.RFC3339Nano
output.PartsOrder = []string{"container", "message"}
output.FormatPartValueByName = func(i interface{}, s string) string {
var ret string
switch s {
case "container":
log := cfg.Color + i.(string) + " =>" + Reset
ret = fmt.Sprintf("%s", log)
}
return ret
}
output.FieldsExclude = []string{"container"}
log := zerolog.New(output).With().Timestamp().Logger()
return &LogWriter{
Logger: &log,
Config: cfg,
stream: stream,
}
}
type LogWriter struct {
Logger *zerolog.Logger
Config Config
stream string
}
func (w LogWriter) Write(p []byte) (n int, err error) {
msg := strings.TrimSpace(string(p))
if msg == "" {
return len(p), nil
}
switch w.stream {
case "stdout":
w.Logger.Info().
Str("container", w.Config.ContainerName).
Msg(msg)
case "stderr":
w.Logger.Error().
Str("container", w.Config.ContainerName).
Msg(msg)
default:
w.Logger.Warn().
Str("container", w.Config.ContainerName).
Msg(fmt.Sprintf("[unknown stream] %s", msg))
}
return len(p), nil
}