-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
85 lines (70 loc) · 1.6 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
package utils
import (
"fmt"
"io"
"os"
"runtime"
"runtime/debug"
"time"
"github.com/k0kubun/pp"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/mgutz/ansi"
)
var goos = runtime.GOOS
// Stdout ...
var Stdout = stdout()
// Stderr ...
var Stderr = stderr()
// Dump ...
func Dump(val interface{}) {
E(pp.Println(val))
}
// Sdump ...
func Sdump(val interface{}) string {
return pp.Sprint(val)
}
// Log log to stdout with timestamp
func Log(v ...interface{}) {
t := time.Now().Format("[2006-01-02 15:04:05]")
v = append([]interface{}{C(t, "7")}, v...)
E(fmt.Fprintln(Stdout, v...))
}
// Err log to stderr with timestamp and stack trace
func Err(v ...interface{}) {
t := time.Now().Format("[2006-01-02 15:04:05]")
v = append(v, "\n"+string(debug.Stack()))
v = append([]interface{}{C(t, "7")}, v...)
E(fmt.Fprintln(Stderr, v...))
}
// ClearScreen ...
func ClearScreen() error {
if goos == "windows" {
_, err := os.Stdout.WriteString("\n\n\n\n\n")
return err
}
print("\033[H\033[2J")
return nil
}
// C color terminal string
func C(str interface{}, color string) string {
return ansi.Color(fmt.Sprint(str), color)
}
func stdout() io.Writer {
if goos == "windows" {
fd := os.Stdout.Fd()
if !isatty.IsTerminal(fd) && !isatty.IsCygwinTerminal(fd) {
return colorable.NewNonColorable(os.Stdout)
}
}
return colorable.NewColorableStdout()
}
func stderr() io.Writer {
if goos == "windows" {
fd := os.Stderr.Fd()
if !isatty.IsTerminal(fd) && !isatty.IsCygwinTerminal(fd) {
return colorable.NewNonColorable(os.Stderr)
}
}
return colorable.NewColorableStderr()
}