From 0bb965325a689d614f1ea948837a3d659a6f2df0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paulo=20Sima=CC=83o?= Date: Tue, 2 Nov 2021 19:06:13 -0300 Subject: [PATCH] 1st ver --- .gitignore | 1 + Readme.md | 5 +++ go.mod | 3 ++ lib.go | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 .gitignore create mode 100644 Readme.md create mode 100644 go.mod create mode 100644 lib.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..901080c --- /dev/null +++ b/Readme.md @@ -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, \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..bf648bd --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module go.digitalcircle.com.br/open/xlog + +go 1.17 diff --git a/lib.go b/lib.go new file mode 100644 index 0000000..42f0a58 --- /dev/null +++ b/lib.go @@ -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() +}