This repository has been archived by the owner on Apr 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
impl.go
97 lines (84 loc) · 2.16 KB
/
impl.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
/*
* Copyright (c) 2020-present unTill Pro, Ltd.
* @author Maxim Geraskin
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package logger
import (
"fmt"
"runtime"
"strings"
"sync/atomic"
"time"
)
const (
globalSkipStackFramesCount = 4
)
const (
errorPrefix = "*****"
warningPrefix = "!!!"
infoPrefix = "==="
verbosePrefix = "---"
tracePrefix = "..."
)
var globalLogPrinter = logPrinter{logLevel: LogLevelInfo}
type logPrinter struct {
logLevel TLogLevel
}
func isEnabled(logLevel TLogLevel) bool {
curLogLevel := TLogLevel(atomic.LoadInt32((*int32)(&globalLogPrinter.logLevel)))
return curLogLevel >= logLevel
}
func (p *logPrinter) getFuncName(skipCount int) (funcName string, line int) {
var fn string
pc, _, line, ok := runtime.Caller(skipCount)
details := runtime.FuncForPC(pc)
if ok && details != nil {
elems := strings.Split(details.Name(), "/")
if len(elems) > 0 {
fn = elems[len(elems)-1]
}
}
return fn, line
}
func (p *logPrinter) getFormattedMsg(msgType string, funcName string, line int, args ...interface{}) string {
t := time.Now()
out := fmt.Sprint(t.Format("01/02 15:04:05.000"))
out += fmt.Sprint(": " + msgType)
out += fmt.Sprintf(": [%v:%v]:", funcName, line)
if len(args) > 0 {
var s string
for _, arg := range args {
s = s + fmt.Sprint(" ", arg)
}
out += fmt.Sprint(s)
}
return out
}
func (p *logPrinter) print(skipStackFrames int, level TLogLevel, msgType string, args ...interface{}) {
funcName, line := p.getFuncName(skipStackFrames + globalSkipStackFramesCount)
out := p.getFormattedMsg(msgType, funcName, line, args...)
PrintLine(level, out)
}
func getLevelPrefix(level TLogLevel) string {
switch level {
case LogLevelError:
return errorPrefix
case LogLevelWarning:
return warningPrefix
case LogLevelInfo:
return infoPrefix
case LogLevelVerbose:
return verbosePrefix
case LogLevelTrace:
return tracePrefix
}
return ""
}
func printIfLevel(skipStackFrames int, level TLogLevel, args ...interface{}) {
if isEnabled(level) {
globalLogPrinter.print(skipStackFrames, level, getLevelPrefix(level), args...)
}
}