blob: 0e214f73e02fa6b73df0caa7a093f7edee0c9371 (
plain)
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
|
package stat_consumer
import (
"encoding/json"
"fmt"
"github.com/mongodb/mongo-tools/mongostat/stat_consumer/line"
)
// JSONLineFormatter converts the StatLines to JSON
type JSONLineFormatter struct {
*limitableFormatter
}
func NewJSONLineFormatter(maxRows int64, _ bool) LineFormatter {
return &JSONLineFormatter{
limitableFormatter: &limitableFormatter{maxRows: maxRows},
}
}
func init() {
FormatterConstructors["json"] = NewJSONLineFormatter
}
func (glf *JSONLineFormatter) Finish() {
}
// FormatLines formats the StatLines as JSON
func (jlf *JSONLineFormatter) FormatLines(lines []*line.StatLine, headerKeys []string, keyNames map[string]string) string {
// middle ground b/t the StatLines and the JSON string to be returned
jsonFormat := map[string]interface{}{}
// convert each StatLine to JSON
for _, l := range lines {
lineJson := make(map[string]interface{})
if l.Printed && l.Error == nil {
l.Error = fmt.Errorf("no data received")
}
l.Printed = true
// check for error
if l.Error != nil {
lineJson["error"] = l.Error.Error()
jsonFormat[l.Fields["host"]] = lineJson
continue
}
for _, key := range headerKeys {
lineJson[keyNames[key]] = l.Fields[key]
}
jsonFormat[l.Fields["host"]] = lineJson
}
// convert the JSON format of the lines to a json string to be returned
linesAsJsonBytes, err := json.Marshal(jsonFormat)
if err != nil {
return fmt.Sprintf(`{"json error": "%v"}`, err.Error())
}
jlf.increment()
return fmt.Sprintf("%s\n", linesAsJsonBytes)
}
|