forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trail.go
108 lines (96 loc) · 2.45 KB
/
trail.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 uadmin
import (
"fmt"
"log"
"runtime/debug"
"strings"
"github.com/PesTospertnyj/uadmin/colors"
)
// Reporting Levels
const (
NONE = 10
DEBUG = 0
WORKING = 1
INFO = 2
OK = 3
WARNING = 4
ERROR = 5
CRITICAL = 6
ALERT = 7
EMERGENCY = 8
)
var trailTag = map[int]string{
NONE: colors.None,
DEBUG: colors.Debug,
WORKING: colors.Working,
INFO: colors.Info,
OK: colors.OK,
WARNING: colors.Warning,
ERROR: colors.Error,
CRITICAL: colors.Critical,
ALERT: colors.Alert,
EMERGENCY: colors.Emergency,
}
var levelMap = map[int]string{
NONE: "",
DEBUG: "[ DEBUG ] ",
WORKING: "[ WORKING] ",
INFO: "[ INFO ] ",
OK: "[ OK ] ",
WARNING: "[ WARNING] ",
ERROR: "[ ERROR ] ",
CRITICAL: "[CRITICAL] ",
ALERT: "[ ALERT ] ",
EMERGENCY: "[ EMERG ] ",
}
var trailBytes = []byte{}
var trailChan = []chan string{} //make(chan string)
// Trail prints to the log
func Trail(level int, msg interface{}, i ...interface{}) {
if level >= ReportingLevel {
message := fmt.Sprint(msg)
if level != WORKING && !strings.HasSuffix(message, "\n") {
message += "\n"
} else if level == WORKING && !strings.HasPrefix(message, "\r") {
message = message + "\r"
}
if ReportTimeStamp {
log.Printf(trailTag[level]+message, i...)
} else {
fmt.Printf(trailTag[level]+message, i...)
}
// Run error handler if it exists
if ErrorHandleFunc != nil {
stack := string(debug.Stack())
stackList := strings.Split(stack, "\n")
stack = strings.Join(stackList[5:], "\n")
go ErrorHandleFunc(level, fmt.Sprintf(fmt.Sprint(msg), i...), stack)
}
// Log to syslog
if LogTrail && level >= TrailLoggingLevel && level != WORKING {
// Send log to syslog
Syslogf(level, message, i...)
}
// Add tail bytes
if level != WORKING {
trailBytes = append(trailBytes, []byte(fmt.Sprintf(trailTag[level]+message, i...))...)
go func(message string) {
for i := len(trailChan) - 1; i >= 0; i-- {
select {
case trailChan[i] <- message:
// fmt.Println("sent " + message)
default:
trailChan = append(trailChan[:i], trailChan[i+1:]...)
fmt.Println("deleted")
}
}
}(fmt.Sprintf(trailTag[level]+message, i...))
if len(trailBytes) > TrailCacheSize {
trailBytes = trailBytes[len(trailBytes)-TrailCacheSize:]
}
}
}
}
func RegisterTrailChan(c chan string) {
trailChan = append(trailChan, c)
}