~tgrosinger/ledger-tui

61ed5836bddd8ae3714f7d640c03a247cfc860bd — Tony Grosinger 1 year, 3 months ago d3077f8
Add flag for debug logging
1 files changed, 27 insertions(+), 6 deletions(-)

M cmd/ledger-tui/ledger-tui.go
M cmd/ledger-tui/ledger-tui.go => cmd/ledger-tui/ledger-tui.go +27 -6
@@ 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)