Skip to content

Commit 635cb2f

Browse files
Added totals feature that shows log size and record count.
-t or --totals
1 parent 7cdc2e9 commit 635cb2f

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

cmd/printlog.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@ THE SOFTWARE.
2222
package cmd
2323

2424
import (
25+
"log"
26+
2527
"github.com/fatih/color"
2628
"github.com/spf13/cobra"
29+
"github.com/spf13/viper"
2730
"github.com/timthreetwelve/bootlogger/utils"
2831
)
2932

@@ -44,7 +47,12 @@ var printlogCmd = &cobra.Command{
4447
}
4548

4649
func init() {
47-
rootCmd.AddCommand(printlogCmd)
48-
// No flags are needed for this command, it just prints the log file
4950
// Output may be large, but can be piped through 'more'
51+
rootCmd.AddCommand(printlogCmd)
52+
53+
// Boolean flag to print totals after the log entries
54+
printlogCmd.Flags().BoolP("totals", "t", false, "Show log file size and total lines after printing log")
55+
if err := viper.BindPFlag("totals", printlogCmd.Flags().Lookup("totals")); err != nil {
56+
log.Printf("Error binding flag 'totals': %v", err)
57+
}
5058
}

utils/printlog.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,16 @@ func PrintLog() error {
6161
defer file.Close()
6262

6363
// Using bufio scanner here for memory-efficient line-by-line reading.
64+
lineCounter := 0
6465
scanner := bufio.NewScanner(file)
6566
for scanner.Scan() {
6667
fmt.Println(scanner.Text())
68+
lineCounter++
69+
}
70+
71+
// Print totals if flag is set
72+
if viper.GetBool("totals") {
73+
fmt.Printf("\n%s is %s and contains %d records.", logFile, formatFileSize(stat.Size()), lineCounter)
6774
}
6875

6976
// Check for errors during scanning
@@ -73,3 +80,26 @@ func PrintLog() error {
7380
}
7481
return nil
7582
}
83+
84+
// Formats a size given in bytes to kb, mb, etc.
85+
func formatFileSize(size int64) string {
86+
const (
87+
KB = 1024
88+
MB = KB * 1024
89+
GB = MB * 1024
90+
TB = GB * 1024
91+
)
92+
93+
switch {
94+
case size >= TB:
95+
return fmt.Sprintf("%.2f TB", float64(size)/float64(TB))
96+
case size >= GB:
97+
return fmt.Sprintf("%.2f GB", float64(size)/float64(GB))
98+
case size >= MB:
99+
return fmt.Sprintf("%.2f MB", float64(size)/float64(MB))
100+
case size >= KB:
101+
return fmt.Sprintf("%.2f KB", float64(size)/float64(KB))
102+
default:
103+
return fmt.Sprintf("%d bytes", size)
104+
}
105+
}

0 commit comments

Comments
 (0)