master
Evan Chen 2021-11-02 15:26:10 +08:00
parent a41e1855ca
commit e247f30f45
3 changed files with 37 additions and 1 deletions

18
log.go
View File

@ -4,6 +4,7 @@ import (
"fmt"
"io"
"os"
"sync"
"text/template"
"time"
@ -26,6 +27,8 @@ const (
twarn
)
var lock sync.Mutex
var PROD = true
var LEVEL = Lerror | Linfo
@ -77,6 +80,8 @@ type Logger struct {
system string
color bool
explicit bool
err io.Writer
out io.Writer
@ -133,9 +138,16 @@ func (l *Logger) guessColor() {
}
}
func (l *Logger) SetColor(c bool) {
l.explicit = true
l.color = c
}
func (l *Logger) SetColorAll(c bool) {
for _, v := range getAllOffsprings(l) {
v.SetColor(c)
}
}
func (l *Logger) SetErrOutput(err io.Writer) {
l.err = err
}
@ -157,7 +169,9 @@ func (l *Logger) SetOutputAll(out io.Writer) {
}
func (l *Logger) Reload() error {
l.guessColor()
if !l.explicit {
l.guessColor()
}
return l.ParseTmpl()
}
@ -233,6 +247,8 @@ func (l *Logger) output(t tout, depth int, stack string, fields H, v ...interfac
Color: l.color,
Stack: stack,
}
lock.Lock()
defer lock.Unlock()
var err error
switch t {
case terror:

View File

@ -98,6 +98,17 @@ func TestToFile(t *testing.T) {
l.WarnF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
l.Info("d", "sdf", "sdfsdf")
l.InfoF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
l.SetColor(true)
l.Reload()
l.Error("d", "sdf", "sdfsdf")
l.ErrorF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
l.Debug("d", "sdf", "sdfsdf")
l.DebugF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
l.Warn("d", "sdf", "sdfsdf")
l.WarnF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
l.Info("d", "sdf", "sdfsdf")
l.InfoF(H{"Test": "set"}, "d", "sdf", "sdfsdf")
}
func TestApplyChild(t *testing.T) {
@ -119,4 +130,9 @@ func TestApplyChild(t *testing.T) {
l1.Info("child1-stdout")
l2.Info("child2-stdout")
l3.Info("child3-stdout")
SetColorAll(false)
ReloadAll()
l1.Info("child1-nocolor")
l2.Info("child2-nocolor")
l3.Info("child3-nocolor")
}

4
std.go
View File

@ -12,6 +12,10 @@ func SetColor(c bool) {
std.SetColor(c)
}
func SetColorAll(c bool) {
std.SetColorAll(c)
}
func SetErrOutput(err io.Writer) {
std.SetErrOutput(err)
}