106 lines
1.7 KiB
Go
106 lines
1.7 KiB
Go
package xlog
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
var envLog string
|
|
var nullLog *log.Logger
|
|
var all bool
|
|
var mx sync.Mutex
|
|
var loggers map[string]*log.Logger
|
|
|
|
func init() {
|
|
envLog = os.Getenv("XLOG")
|
|
loggers = make(map[string]*log.Logger)
|
|
logs := strings.Split(envLog, ",")
|
|
for _, v := range logs {
|
|
if v == "ALL" {
|
|
all = true
|
|
}
|
|
loggers[v] = log.New(log.Writer(), v, log.Flags())
|
|
}
|
|
|
|
nullLog = log.New(io.Discard, "", 0)
|
|
}
|
|
func Logger(n string) *log.Logger {
|
|
ret, ok := loggers[n]
|
|
if ok {
|
|
return ret
|
|
}
|
|
if all {
|
|
mx.Lock()
|
|
defer mx.Unlock()
|
|
|
|
if ok {
|
|
return ret
|
|
}
|
|
ret = log.New(log.Writer(), n+" - ", log.Flags())
|
|
loggers[n] = ret
|
|
return ret
|
|
|
|
} else {
|
|
mx.Lock()
|
|
defer mx.Unlock()
|
|
loggers[n] = nullLog
|
|
}
|
|
|
|
return nullLog
|
|
}
|
|
func Loggers() map[string]bool {
|
|
ret := make(map[string]bool)
|
|
for k, v := range loggers {
|
|
ret[k] = v != nullLog
|
|
}
|
|
return ret
|
|
}
|
|
func Enable(n string) *log.Logger {
|
|
ret, ok := loggers[n]
|
|
if ok {
|
|
return ret
|
|
}
|
|
|
|
ret = log.New(log.Writer(), n, log.Flags())
|
|
loggers[n] = ret
|
|
return ret
|
|
|
|
}
|
|
func Disable(n string) {
|
|
loggers[n] = nullLog
|
|
}
|
|
|
|
func Log() *log.Logger {
|
|
return &log.Logger{}
|
|
}
|
|
func Debug() *log.Logger {
|
|
return Logger("debug")
|
|
}
|
|
|
|
func Trace() *log.Logger {
|
|
return Logger("trace")
|
|
}
|
|
|
|
func Warn() *log.Logger {
|
|
return Logger("warm")
|
|
}
|
|
|
|
func Fatal() *log.Logger {
|
|
return Logger("fatal")
|
|
}
|
|
|
|
func Status() string {
|
|
sb := strings.Builder{}
|
|
sb.WriteString(fmt.Sprintf("XLOG STATUS:\n"))
|
|
sb.WriteString(fmt.Sprintf(" LOGGER - ENABLE\n"))
|
|
for k, v := range Loggers() {
|
|
sb.WriteString(fmt.Sprintf(" %s - %v\n", k, v))
|
|
}
|
|
sb.WriteString(fmt.Sprintf("ALL enabled: %v\n", all))
|
|
return sb.String()
|
|
}
|