Skip to content

Commit

Permalink
change: tool Console now prints package instead of relative filepath
Browse files Browse the repository at this point in the history
  • Loading branch information
iamwavecut committed Jun 8, 2024
1 parent 304b1f8 commit cacf6f4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
21 changes: 16 additions & 5 deletions tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
"golang.org/x/exp/slices"
"html/template"
stdlog "log"
"math/big"
Expand All @@ -16,6 +15,8 @@ import (
"strings"
"time"

"golang.org/x/exp/slices"

"golang.org/x/exp/constraints"
)

Expand Down Expand Up @@ -60,11 +61,21 @@ func getRelativePath(filePath string) string {

// Console Prints %+v of arguments, great to debug stuff
func Console(obj ...interface{}) {
// get caller file path
_, file, line, _ := runtime.Caller(1)
pc, _, line, ok := runtime.Caller(1)
if !ok {
tooloLog.LogError(errors.New("unable to get caller information"))
return
}
fn := runtime.FuncForPC(pc)
if fn == nil {
tooloLog.LogError(errors.New("unable to get function information"))
return
}
pkg := strings.Split(fn.Name(), "/")
pkgName := strings.Join(pkg[0:len(pkg)-1], "/") + "/"
pkgName += strings.Split(pkg[len(pkg)-1:][0], ".")[0]

relPath := getRelativePath(file)
prefix := fmt.Sprintf("[%s:%d]>", relPath, line)
prefix := fmt.Sprintf("[%s:%d]>", pkgName, line)
tooloLog.LogDeep(append([]interface{}{prefix}, obj...)...)
}

Expand Down
6 changes: 3 additions & 3 deletions tool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,17 @@ func (s *ToolTestSuite) TestIn() {
func (s *ToolTestSuite) TestConsole() {
s.Run("1", func() {
Console("123", "456", "789")
s.Equal("[tool_test.go:65]> 123 456 789\n", testLog.buf)
s.Equal("[github.com/iamwavecut/tool:65]> 123 456 789\n", testLog.buf)
})
s.Run("2", func() {
testLog.buf = ""
Console(struct{ int }{123})
s.Equal("[tool_test.go:70]> {int:123}\n", testLog.buf)
s.Equal("[github.com/iamwavecut/tool:70]> {int:123}\n", testLog.buf)
})
s.Run("3", func() {
testLog.buf = ""
Console(nil)
s.Equal("[tool_test.go:75]> <nil>\n", testLog.buf)
s.Equal("[github.com/iamwavecut/tool:75]> <nil>\n", testLog.buf)
})
}

Expand Down

0 comments on commit cacf6f4

Please sign in to comment.