Skip to content

Commit bc02c16

Browse files
committed
improve the CLI tool output formatting
1 parent 5318844 commit bc02c16

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

cmd/logparser.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,15 @@ import (
99
"io"
1010
"os"
1111
"sort"
12+
"strconv"
1213
"strings"
1314
"time"
1415
)
1516

1617
func main() {
1718
screenWidth := flag.Int("w", 120, "terminal width")
19+
maxLinesPerMessage := flag.Int("l", 100, "max lines per message")
20+
1821
flag.Parse()
1922

2023
reader := bufio.NewReader(os.Stdin)
@@ -38,7 +41,7 @@ func main() {
3841

3942
order(counters)
4043

41-
output(counters, *screenWidth, d)
44+
output(counters, *screenWidth, *maxLinesPerMessage, d)
4245
}
4346

4447
func order(counters []logparser.LogCounter) {
@@ -51,7 +54,7 @@ func order(counters []logparser.LogCounter) {
5154
})
5255
}
5356

54-
func output(counters []logparser.LogCounter, screenWidth int, duration time.Duration) {
57+
func output(counters []logparser.LogCounter, screenWidth, maxLinesPerMessage int, duration time.Duration) {
5558
grandTotal, total, max := 0, 0, 0
5659
for _, c := range counters {
5760
grandTotal += c.Messages
@@ -63,22 +66,23 @@ func output(counters []logparser.LogCounter, screenWidth int, duration time.Dura
6366
max = c.Messages
6467
}
6568
}
66-
barWidth := 30
69+
barWidth := 20
6770
lineWidth := screenWidth - barWidth
71+
messagesNumFmt := fmt.Sprintf("%%%dd", len(strconv.Itoa(max)))
6872
for _, c := range counters {
6973
if c.Sample == "" {
7074
continue
7175
}
7276
w := c.Messages * barWidth / max
7377
bar := strings.Repeat("▇", w+1) + strings.Repeat(" ", barWidth-w)
74-
prefix := colorize(c.Level, "%s %d (%.2f%%)\t", bar, c.Messages, float64(c.Messages*100)/float64(total))
78+
prefix := colorize(c.Level, "%s "+messagesNumFmt+" (%2d%%) ", bar, c.Messages, int(float64(c.Messages*100)/float64(total)))
7579
sample := ""
7680
for i, line := range strings.Split(c.Sample, "\n") {
7781
if len(line) > lineWidth {
7882
line = line[:lineWidth] + "..."
7983
}
8084
sample += line + "\n" + strings.Repeat(" ", len(prefix))
81-
if i > 10 {
85+
if i > maxLinesPerMessage {
8286
sample += "...\n"
8387
break
8488
}

0 commit comments

Comments
 (0)