-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
114 lines (104 loc) · 1.96 KB
/
log.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
109
110
111
112
113
114
package main
import (
"fmt"
"log"
"os"
"path"
"runtime"
"github.com/abakum/menu"
"github.com/xlab/closer"
)
var (
letf = log.New(os.Stdout, menu.BUG, log.Ltime|log.Lshortfile)
let = log.New(os.Stdout, menu.BUG, log.Ltime)
ltf = log.New(os.Stdout, " ", log.Ltime|log.Lshortfile)
lt = log.New(os.Stdout, " ", log.Ltime)
li = log.New(os.Stdout, "\t", 0)
)
// Colorable log
func SetColor() {
bug, _, out := menu.BugGtOut()
letf.SetOutput(out)
let.SetOutput(out)
letf.SetPrefix(bug)
let.SetPrefix(bug)
}
// Get source of code
func src(depth int) (s string) {
pc := make([]uintptr, 1)
n := runtime.Callers(depth-5, pc)
if n > 0 {
frame, _ := runtime.CallersFrames(pc).Next()
s = fmt.Sprintf("%s:%d:", path.Base(frame.File), frame.Line)
}
return
}
// Wrap source of code and message to error
func Errorf(format string, args ...any) error {
return fmt.Errorf(src(8)+" %w", fmt.Errorf(format, args...))
}
// Wrap source of code and error to error
func srcError(err error) error {
if err == nil {
return nil
}
return fmt.Errorf(src(8)+" %w", err)
}
func PrintOk(s string, err error) (ok bool) {
ok = err == nil
if ok {
lt.Println(src(8), s, "ok")
} else {
let.Println(src(8), s, err)
}
return ok
}
func Println(v ...any) (ok bool) {
anys := []any{src(8)}
ok = true
for _, a := range v {
switch t := a.(type) {
case nil:
anys = append(anys, "Ф")
case error:
anys = append(anys, t)
ok = false
case string:
if t != "" {
anys = append(anys, t)
}
default:
anys = append(anys, t)
}
}
if ok {
lt.Println(anys...)
} else {
let.Println(anys...)
}
return ok
}
func Fatal(err error) {
if err != nil {
let.Println(src(8), err)
closer.Exit(1)
}
}
func FatalOr(s string, cases ...bool) {
for _, c := range cases {
if c {
let.Println(src(8), s)
closer.Exit(1)
break
}
}
}
func FatalAnd(s string, cases ...bool) {
for _, c := range cases {
if !c {
return
}
}
let.Println(src(8), s)
closer.Exit(1)
}