-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump.go
108 lines (94 loc) · 1.94 KB
/
dump.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package dump
import (
"fmt"
"runtime"
"strings"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/fatih/color"
)
// P
// alias VarDump()
func P(vals ...interface{}) {
VarDump(vals...)
}
func VarDump(vals ...interface{}) {
ColorDump(color.New(color.FgRed).Add(color.BgHiWhite), vals...)
}
// ColorDump
// c := color.New(color.FgCyan).Add(color.Underline)
// c := color.New(color.FgCyan, color.Bold)
// https://github.com/fatih/color
func ColorDump(c *color.Color, vals ...interface{}) {
if c == nil {
Dump(vals...)
return
}
commonPrintln(c.Println, vals...)
}
func Printf(format string, a ...interface{}) {
s := fmt.Sprintf(format, a...)
tnow := timeNow()
file := debugTrace()
c := color.New(color.FgRed).Add(color.BgYellow)
c.Printf("%s %s \n%s", tnow, file, s)
return
}
// Println
// alias Dump()
func Println(vals ...interface{}) {
Dump(vals...)
}
// Dump
// The same as PHP:var_dump()
// https://www.php.net/var_dump
func Dump(vals ...interface{}) {
commonPrintln(fmt.Println, vals...)
}
// JsonDump
func JsonDump(v interface{}) string {
return gabs.Wrap(v).StringIndent("", " ")
}
type F func(...interface{}) (int, error)
func commonPrintln(f F, vals ...interface{}) {
tnow := timeNow()
file := debugTrace()
f(tnow, file)
for _, v := range vals {
f(JsonDump(v))
}
}
func timeNow() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func Traces() []string {
i := 0
ret := make([]string, 0, 10)
funcName := ""
for {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fc := runtime.FuncForPC(pc)
if fc != nil {
funcName = fc.Name()
if pos := strings.LastIndex(funcName, "/"); pos > 0 {
funcName = funcName[pos+1:]
}
}
ret = append(ret, fmt.Sprintf("%s:%d:%s()", file, line, funcName))
i++
}
return ret
}
func debugTrace() string {
traces := Traces()
for _, line := range traces {
if pos := strings.Index(line, "dump.go:"); pos != -1 {
continue
}
return line
}
return ""
}