Skip to content

Commit

Permalink
refactor(log): capture commands
Browse files Browse the repository at this point in the history
  • Loading branch information
natesales committed Sep 4, 2024
1 parent 7fb570d commit 1eda163
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 25 deletions.
3 changes: 1 addition & 2 deletions cmd/birdsh.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"bufio"
"fmt"
"net"
"os"
"strings"
Expand Down Expand Up @@ -50,7 +49,7 @@ var birdshCmd = &cobra.Command{

r := bufio.NewReader(os.Stdin)
for {
fmt.Print("bird> ")
log.Printf("bird> ")
cmd, _ := r.ReadString('\n')
cmd = strings.ReplaceAll(cmd, "\n", "")
if cmd != "" {
Expand Down
4 changes: 2 additions & 2 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ var configCmd = &cobra.Command{
buf += "# Config"
}
buf += fmt.Sprintf(" exported from %s on %s\n", configFile, time.Now().Format(time.RFC822Z))
fmt.Println(buf)
log.Println(buf)

if sanitize {
// Apply sanitized keys
Expand All @@ -86,7 +86,7 @@ var configCmd = &cobra.Command{

logknife.Knife(bytes.NewBuffer([]byte(config)), false, true, false, "")
} else {
fmt.Print(config)
log.Println(config)
}
},
}
23 changes: 17 additions & 6 deletions cmd/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,23 @@ package cmd

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/natesales/pathvector/pkg/util/log"
)

func TestConfig(t *testing.T) {
rootCmd.SetArgs([]string{
"config",
"-c", "../tests/generate-complex.yml",
})
if err := rootCmd.Execute(); err != nil {
t.Error(err)
}

out := log.Capture()
defer log.ResetCapture()
assert.Nil(t, rootCmd.Execute())
assert.Contains(t, out.String(), "# Pathvector devel")
assert.Contains(t, out.String(), "asn: 65530")
}

func TestSanitizeConfig(t *testing.T) {
Expand All @@ -20,7 +27,11 @@ func TestSanitizeConfig(t *testing.T) {
"-c", "../tests/generate-complex.yml",
"--sanitize",
})
if err := rootCmd.Execute(); err != nil {
t.Error(err)
}

out := log.Capture()
defer log.ResetCapture()
assert.Nil(t, rootCmd.Execute())
assert.Contains(t, out.String(), "# Pathvector devel")
assert.Contains(t, out.String(), "asn: 65530")
assert.Contains(t, out.String(), "- 2001:db8:")
}
3 changes: 2 additions & 1 deletion cmd/ctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/lithammer/fuzzysearch/fuzzy"

"github.com/natesales/pathvector/pkg/templating"
"github.com/natesales/pathvector/pkg/util/log"
)

func protocols(birdDirectory string) (map[string]*templating.Protocol, error) {
Expand Down Expand Up @@ -60,7 +61,7 @@ func protocolByQuery(query string, protocols map[string]*templating.Protocol) (s

// confirmYesNo asks a [y/N] question and returns true if the user selects yes
func confirmYesNo(question string) bool {
fmt.Printf("%s [y/N] ", question)
log.Printf("%s [y/N] ", question)
var response string
_, _ = fmt.Scanln(&response)
return response == "y" || response == "Y"
Expand Down
2 changes: 1 addition & 1 deletion cmd/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var dumpCmd = &cobra.Command{
if err != nil {
log.Fatal(err)
}
fmt.Println(string(yamlBytes))
log.Println(string(yamlBytes))
} else {
var data [][]string
for peerName, peerData := range c.Peers {
Expand Down
3 changes: 1 addition & 2 deletions cmd/match.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"fmt"
"strconv"
"strings"

Expand Down Expand Up @@ -47,6 +46,6 @@ var matchCmd = &cobra.Command{
log.Fatal(err)
}

fmt.Println(match.CommonIXs(uint32(matchLocalASN), uint32(peerASN), yamlFormat, peeringDbTimeout, c.PeeringDBAPIKey))
log.Println(match.CommonIXs(uint32(matchLocalASN), uint32(peerASN), yamlFormat, peeringDbTimeout, c.PeeringDBAPIKey))
},
}
2 changes: 1 addition & 1 deletion cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ var statusCmd = &cobra.Command{
if err != nil {
log.Fatal(err)
}
fmt.Println(commandOutput)
log.Println(commandOutput)
} else {
commandOutput, _, err := bird.RunCommand("show protocols all", c.BIRDSocket)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Built %s on %s
}

func printVersionBanner() {
fmt.Println(versionBanner())
log.Println(versionBanner())
}

var versionCmd = &cobra.Command{
Expand All @@ -58,6 +58,6 @@ var versionCmd = &cobra.Command{
if err != nil {
log.Fatal(err)
}
fmt.Printf("BIRD: %s\n", birdVersion)
log.Printf("BIRD: %s\n", birdVersion)
},
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ require (
github.com/lithammer/fuzzysearch v1.1.8
github.com/natesales/logknife v0.0.4-0.20230403055117-5e928ad4153b
github.com/olekukonko/tablewriter v0.0.5
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.9.0
golang.org/x/mod v0.19.0
Expand All @@ -37,6 +36,7 @@ require (
github.com/muesli/termenv v0.15.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/exp v0.0.0-20240707233637-46b078467d37 // indirect
Expand Down
10 changes: 5 additions & 5 deletions pkg/autodoc/documentation.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (s byReflectType) Less(i, j int) bool {
func documentConfigTypes(t reflect.Type, output bool) {
childTypesSet := map[reflect.Type]bool{}
if output {
fmt.Println("## " + sanitizeConfigName(t.String()))
log.Println("## " + sanitizeConfigName(t.String()))
}
// Handle pointer types
if t.Kind() == reflect.Ptr {
Expand All @@ -69,7 +69,7 @@ func documentConfigTypes(t reflect.Type, output bool) {
}
}
if output {
fmt.Printf(`### `+"`"+`%s`+"`"+`
log.Printf(`### `+"`"+`%s`+"`"+`
%s
Expand All @@ -79,11 +79,11 @@ func documentConfigTypes(t reflect.Type, output bool) {
`, key, description, addLink(sanitizeConfigName(field.Type.String())), fDefault, validation)
}
// fmt.Printf("| %s | %s | %s | %s | %s |\n", key, addLink(sanitizeConfigName(field.Type.String())), fDefault, validation, description)
// log.Printf("| %s | %s | %s | %s | %s |\n", key, addLink(sanitizeConfigName(field.Type.String())), fDefault, validation, description)
}
}
if output {
fmt.Println()
log.Println()
}

// Convert the set into a slice and sort it
Expand All @@ -101,7 +101,7 @@ func documentConfigTypes(t reflect.Type, output bool) {
// DocumentConfig prints a YAML file with autogenerated configuration documentation
func DocumentConfig(output bool) {
if output {
fmt.Println("# Configuration")
log.Println("# Configuration")
}
documentConfigTypes(reflect.TypeOf(config.Config{}), output)
}
2 changes: 1 addition & 1 deletion pkg/bird/bird.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func ReadClean(r io.Reader) {
resp = strings.ReplaceAll(resp, "\n\n", "\n")
resp = strings.TrimSuffix(resp, "\n")

fmt.Println(resp)
log.Println(resp)
}

// RunCommand runs a BIRD command and returns the output, version, and error
Expand Down
28 changes: 27 additions & 1 deletion pkg/util/log/log.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package log

import (
"bytes"
"fmt"
"io"
"os"

"github.com/charmbracelet/log"
Expand All @@ -18,12 +20,36 @@ const (
FatalLevel = Level(log.FatalLevel)
)

var logger = log.Default()
var (
logger = log.Default()
writer io.Writer = os.Stdout
)

func SetLevel(l Level) {
logger.SetLevel(log.Level(l))
}

func Capture() *bytes.Buffer {
var buf bytes.Buffer
writer = &buf
logger.SetOutput(writer)
return &buf
}

func ResetCapture() {
logger.SetOutput(os.Stderr)
writer = os.Stdout
}

// Println prints a line with no formatting or timestamp or anything
func Println(msg ...any) {
_, _ = fmt.Fprintln(writer, msg...)
}

func Printf(format string, args ...any) {
_, _ = fmt.Fprintf(writer, format, args...)
}

// Trace logs a trace message.
func Trace(msg interface{}, keyvals ...any) {
logger.Log(log.Level(TraceLevel), msg, keyvals...)
Expand Down

0 comments on commit 1eda163

Please sign in to comment.