master
Paulo Simão 2021-11-02 19:06:13 -03:00
commit 0bb965325a
4 changed files with 114 additions and 0 deletions

1
.gitignore vendored 100644
View File

@ -0,0 +1 @@
.idea

5
Readme.md 100644
View File

@ -0,0 +1,5 @@
#xlog
This package allows better log control through the application
Once you set XLOG ENV VAR, either you name each log you want or set it to ALL,

3
go.mod 100644
View File

@ -0,0 +1,3 @@
module go.digitalcircle.com.br/open/xlog
go 1.17

105
lib.go 100644
View File

@ -0,0 +1,105 @@
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()
}