Add flag for debug logging

This commit is contained in:
Tony Grosinger 2022-08-05 08:13:56 -07:00
parent d3077f83b7
commit 61ed5836bd

View File

@ -2,6 +2,8 @@ package main
import (
"fmt"
"io"
"log"
"os"
tea "github.com/charmbracelet/bubbletea"
@ -12,19 +14,38 @@ import (
)
var rootCmd = &cobra.Command{
Use: "ledger-tui",
Short: "An interactive terminal UI for ledger",
Use: "ledger-tui",
Short: "An interactive terminal UI for ledger",
PersistentPreRun: configureLogging,
PersistentPostRun: loggingCleanup,
}
func main() {
if len(os.Getenv("DEBUG")) > 0 {
f, err := tea.LogToFile("debug.log", "debug")
var debugLogging bool
var debugLoggingFile *os.File
func configureLogging(_ *cobra.Command, _ []string) {
if debugLogging {
var err error
debugLoggingFile, err = tea.LogToFile("debug.log", "debug")
if err != nil {
fmt.Println("fatal:", err)
os.Exit(1)
}
defer f.Close()
} else {
log.SetOutput(io.Discard)
}
}
func loggingCleanup(_ *cobra.Command, _ []string) {
if debugLoggingFile != nil {
debugLoggingFile.Close()
debugLoggingFile = nil
}
}
func main() {
rootCmd.PersistentFlags().BoolVar(&debugLogging, "debug", false,
"Output debug logs to debug.log file")
rootCmd.AddCommand(add.AddCmd)
rootCmd.AddCommand(license.LicenseCmd)