-
Notifications
You must be signed in to change notification settings - Fork 6
/
debug.go
111 lines (96 loc) · 2.21 KB
/
debug.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
package main
import (
"fmt"
"log"
"log/syslog"
"os"
"path"
"runtime"
"strconv"
// #include <stdio.h>
// #include <unistd.h>
// #include <string.h>
"C"
)
// Create logger object
const (
logFlags = log.Ldate | log.Ltime // | log.Lshortfile
)
var (
debugLogger = log.New(os.Stderr, "", logFlags)
debugLevel = 0
prefixFmt = ""
formatMap = map[bool]string{
true: "\033[33mDEBUG L%d [%s:%d]\033[0m \t",
false: "DEBUG L%d [%s:%d] \t",
}
fuseFmt = ""
fuseFormatMap = map[bool]string{
true: "\033[36mFUSE\033[0m %s",
false: "FUSE %s",
}
)
func init() {
// Determine if output format to use according to the destination of the
// debug messages. If stderr is a terminal we can use colors
prefixFmt = formatMap[isTerminal(os.Stderr)]
fuseFmt = fuseFormatMap[isTerminal(os.Stderr)]
// Set the debug level from the environmental variable
if env := os.Getenv("CLUEFS_DEBUG"); env != "" {
if value, err := strconv.ParseInt(env, 10, 32); err == nil {
debugLevel = clamp(int(value), 0, 5)
}
}
}
// Set the debug level
func SetLevel(level int) {
debugLevel = level
}
func IsDebugActive() bool {
return debugLevel > 0
}
// Show a debug message
func Debug(level int, format string, v ...interface{}) {
if debugLevel > 0 && level <= debugLevel {
_, file, line, _ := runtime.Caller(1)
debugLogger.SetPrefix(fmt.Sprintf(prefixFmt, level, path.Base(file), line))
debugLogger.Printf(format, v...)
}
}
// Show a FUSE level debug message
func FuseDebug(msg interface{}) {
Debug(4, fuseFmt, msg)
}
// Send debug message to syslog facility
func ToSyslog() {
syslogger, err := syslog.NewLogger(syslog.LOG_ERR|syslog.LOG_USER, 0)
if err == nil {
debugLogger = syslogger
prefixFmt = formatMap[false]
fuseFmt = fuseFormatMap[false]
}
}
func isTerminal(file *os.File) bool {
if C.isatty(C.int(file.Fd())) == 0 {
return false
}
return true
}
// Returns the minimum value among two integers
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
// Returns the maximum value among two integers
func maxInt(a, b int) int {
if a < b {
return b
}
return a
}
// Keeps a given value within the specified interval
func clamp(val, min, max int) int {
return minInt(maxInt(min, val), max)
}