From 0df5170a1e4443da60ef999b316256c63eef3ea2 Mon Sep 17 00:00:00 2001 From: xjasonlyu Date: Wed, 28 Aug 2024 18:51:48 -0400 Subject: [PATCH] emitter --- log/emitter.go | 25 ++++++++++--------------- log/log.go | 1 + main.go | 2 +- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/log/emitter.go b/log/emitter.go index 328a103f..8312edb1 100644 --- a/log/emitter.go +++ b/log/emitter.go @@ -1,7 +1,6 @@ package log import ( - "io" "runtime" "strings" "time" @@ -9,26 +8,22 @@ import ( glog "gvisor.dev/gvisor/pkg/log" ) +var _globalE = &emitter{} + func init() { - EnableStackLog(true) + glog.SetTarget(_globalE) } -func EnableStackLog(v bool) { - if v { - glog.SetTarget(&emitter{}) // built-in logger - } else { - glog.SetTarget(&glog.Writer{Next: io.Discard}) - } +type emitter struct { + logger *SugaredLogger } -type emitter struct{} - -func (*emitter) level(level glog.Level) Level { - return 1 - Level(level) +func (e *emitter) setLogger(logger *SugaredLogger) { + e.logger = logger.WithOptions(pkgCallerSkip) } -func (*emitter) prefix(format string) string { - return "[STACK] " + format +func (e *emitter) logf(level glog.Level, format string, args ...any) { + e.logger.Logf(1-Level(level), "[STACK] "+format, args...) } func (e *emitter) Emit(depth int, level glog.Level, _ time.Time, format string, args ...any) { @@ -38,5 +33,5 @@ func (e *emitter) Emit(depth int, level glog.Level, _ time.Time, format string, return } } - logf(e.level(level), e.prefix(format), args...) + e.logf(level, format, args...) } diff --git a/log/log.go b/log/log.go index 6d6dab4d..9b44fa31 100644 --- a/log/log.go +++ b/log/log.go @@ -40,6 +40,7 @@ func SetLogger(logger *Logger) { // apply pkgCallerSkip to global loggers. _globalL = logger.WithOptions(pkgCallerSkip) _globalS = _globalL.Sugar() + _globalE.setLogger(_globalS) } func logf(lvl Level, template string, args ...any) { diff --git a/main.go b/main.go index a7c08e4c..201c396d 100644 --- a/main.go +++ b/main.go @@ -30,7 +30,7 @@ func init() { flag.StringVar(&configFile, "config", "", "YAML format configuration file") flag.StringVar(&key.Device, "device", "", "Use this device [driver://]name") flag.StringVar(&key.Interface, "interface", "", "Use network INTERFACE (Linux/MacOS only)") - flag.StringVar(&key.LogLevel, "loglevel", "info", "Log level [debug|info|warning|error|silent]") + flag.StringVar(&key.LogLevel, "loglevel", "info", "Log level [debug|info|warn|error|silent]") flag.StringVar(&key.Proxy, "proxy", "", "Use this proxy [protocol://]host[:port]") flag.StringVar(&key.RestAPI, "restapi", "", "HTTP statistic server listen address") flag.StringVar(&key.TCPSendBufferSize, "tcp-sndbuf", "", "Set TCP send buffer size for netstack")