perf: use single tmpl

master v0.0.1
Evan Chen 2021-11-04 10:35:56 +08:00
parent aec6140802
commit f5a1ba9c18
3 changed files with 22 additions and 20 deletions

3
.gitignore vendored
View File

@ -1 +1,2 @@
dist
dist
tests

View File

@ -1 +1,6 @@
# Logging with color and format string
# Logging with color and format string
## Test
Mem: `go test -o tests/test.exe -memprofile tests/mem && go tool pprof -http : tests/mem`
Cpu: `go test -o tests/test.exe -cpuprofile tests/cpu && go tool pprof -http : tests/cpu`

32
log.go
View File

@ -86,8 +86,10 @@ type Logger struct {
err io.Writer
out io.Writer
formatter *LogFormater
funcMap template.FuncMap
formatter *LogFormater
funcMap template.FuncMap
tmpl *template.Template
err_tmpl *template.Template
debug_tmpl *template.Template
warn_tmpl *template.Template
@ -115,10 +117,7 @@ func (l *Logger) Sub(sys string) *Logger {
color: l.color,
formatter: l.formatter,
err_tmpl: l.err_tmpl,
debug_tmpl: l.debug_tmpl,
warn_tmpl: l.warn_tmpl,
info_tmpl: l.info_tmpl,
tmpl: l.tmpl,
}
if l.subs == nil {
l.subs = make([]*Logger, 0)
@ -209,26 +208,23 @@ func (l *Logger) ParseTmpl() error {
funcMap := copyFuncMap(l.funcMap)
l.setColorMap(funcMap)
err_tmpl, err := template.New("err_tmpl").Funcs(funcMap).Parse(l.formatter.ErrTmplStr)
tmpl, err := template.New("info_tmpl").Funcs(funcMap).Parse(l.formatter.InfoTmplStr)
if err != nil {
return err
}
l.err_tmpl = err_tmpl
warn_tmpl, err := template.New("warn_tmpl").Funcs(funcMap).Parse(l.formatter.WarnTmplStr)
tmpl, err = tmpl.New("err_tmpl").Parse(l.formatter.ErrTmplStr)
if err != nil {
return err
}
l.warn_tmpl = warn_tmpl
info_tmpl, err := template.New("info_tmpl").Funcs(funcMap).Parse(l.formatter.InfoTmplStr)
tmpl, err = tmpl.New("warn_tmpl").Parse(l.formatter.WarnTmplStr)
if err != nil {
return err
}
l.info_tmpl = info_tmpl
debug_tmpl, err := template.New("debug_tmpl").Funcs(funcMap).Parse(l.formatter.DebugTmplStr)
tmpl, err = tmpl.New("debug_tmpl").Parse(l.formatter.DebugTmplStr)
if err != nil {
return err
}
l.debug_tmpl = debug_tmpl
l.tmpl = tmpl
return nil
}
@ -257,22 +253,22 @@ func (l *Logger) output(t tout, depth int, stack string, fields H, v ...interfac
if LEVEL&Lerror == 0 {
return
}
err = l.err_tmpl.Execute(l.err, data)
err = l.tmpl.ExecuteTemplate(l.err, "err_tmpl", data)
case tdebug:
if LEVEL&Ldebug == 0 {
return
}
err = l.debug_tmpl.Execute(l.err, data)
err = l.tmpl.ExecuteTemplate(l.err, "debug_tmpl", data)
case twarn:
if LEVEL&Lwarn == 0 {
return
}
err = l.warn_tmpl.Execute(l.out, data)
err = l.tmpl.ExecuteTemplate(l.out, "warn_tmpl", data)
case tinfo:
if LEVEL&Linfo == 0 {
return
}
err = l.info_tmpl.Execute(l.out, data)
err = l.tmpl.ExecuteTemplate(l.out, "info_tmpl", data)
}
if err != nil {
fmt.Fprintln(l.err, "[FATAL] Logger error:", err)