-
Notifications
You must be signed in to change notification settings - Fork 2
/
console_dest.go
105 lines (94 loc) · 1.99 KB
/
console_dest.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package engine
import (
"encoding/json"
"fmt"
"github.com/olekukonko/tablewriter"
"io"
"os"
"time"
)
const ConsoleDestinationName = "CONSOLE"
type ConsoleDestination struct {
Name string
FormatAsJSON bool
Writer io.Writer
cols []string
result [][]string
resultInt [][]interface{}
}
func (cd *ConsoleDestination) Ping() error { return nil }
func (cd *ConsoleDestination) Open(s Stream, l Logger, st Stopper) {
if cd.Writer == nil {
cd.Writer = os.Stderr
}
if cd.Name == "" {
cd.Name = ConsoleDestinationName
}
inChan := s.Chan(cd.Name)
l.Chan() <- Event{
Source: cd.Name,
Level: Trace,
Time: time.Now(),
Message: "Console destination opened",
}
var firstTime = true
for msg := range inChan {
if firstTime {
firstTime = false
cd.cols = s.Columns()
}
if cd.FormatAsJSON {
cd.resultInt = append(cd.resultInt, msg.Data)
continue
}
var s []string
for _, i := range msg.Data {
s = append(s, fmt.Sprintf("%v", i))
}
cd.result = append(cd.result, s)
}
l.Chan() <- Event{
Source: cd.Name,
Level: Info,
Time: time.Now(),
Message: fmt.Sprintf("Processed %v rows", len(cd.result)),
}
if cd.FormatAsJSON {
s, err := cd.marshal()
if err != nil {
l.Chan() <- Event{
Source: cd.Name,
Level: Error,
Time: time.Now(),
Message: fmt.Sprintf("could not marshal %v", err),
}
return
}
cd.Writer.Write([]byte(s))
return
}
table := tablewriter.NewWriter(cd.Writer)
table.SetHeader(cd.cols)
for _, v := range cd.result {
table.Append(v)
}
table.Render()
l.Chan() <- Event{
Source: cd.Name,
Level: Info,
Time: time.Now(),
Message: "Console destination closed",
}
}
func (cd *ConsoleDestination) marshal() (string, error) {
var ret []map[string]interface{}
for i := range cd.resultInt {
r := make(map[string]interface{})
for j, col := range cd.resultInt[i] {
r[cd.cols[j]] = col
}
ret = append(ret, r)
}
b, err := json.Marshal(ret)
return string(b), err
}