-
Notifications
You must be signed in to change notification settings - Fork 64
/
colorful_consumer.go
51 lines (41 loc) · 1.29 KB
/
colorful_consumer.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package logs
import (
"fmt"
rainbow "kraftkit.sh/internal/rainbowprint"
"kraftkit.sh/iostreams"
)
type LogConsumer interface {
Consume(line ...string)
}
type ColorfulConsumer struct {
streams *iostreams.IOStreams
color rainbow.ColorFunc
prefix string
}
// NewColorfulConsumer creates a new log consumer which prefixes each line with a colorful prefix.
func NewColorfulConsumer(streams *iostreams.IOStreams, color bool, prefix string) (*ColorfulConsumer, error) {
if streams == nil {
return nil, fmt.Errorf("cannot create a colorful consumer with nil IOStreams")
}
var colorFunc rainbow.ColorFunc
if color {
rainbow.SetANSIMode(streams, rainbow.Auto)
} else {
rainbow.SetANSIMode(streams, rainbow.Never)
}
colorFunc = rainbow.NextColor()
return &ColorfulConsumer{streams: streams, color: colorFunc, prefix: prefix}, nil
}
// Consume implements logConsumer
func (c *ColorfulConsumer) Consume(strs ...string) {
for _, s := range strs {
if c.prefix != "" {
s = fmt.Sprintf("%s | %s", c.color(c.prefix), s)
}
fmt.Fprintf(c.streams.Out, "%s\n", s)
}
}