From 2e6a23743b73cd514411c0c647dbdb6acfd9753b Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:37:56 +0800 Subject: [PATCH 01/20] refactor logs package --- logs/log.go | 178 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 167 insertions(+), 11 deletions(-) diff --git a/logs/log.go b/logs/log.go index 583b35e0..1ec7dd1d 100644 --- a/logs/log.go +++ b/logs/log.go @@ -35,10 +35,12 @@ package logs import ( "fmt" + "log" "os" "path" "runtime" "strconv" + "strings" "sync" "time" ) @@ -55,6 +57,15 @@ const ( LevelDebug ) +const ( + AdapterConsole = "console" + AdapterFile = "file" + AdapterMultiFile = "multifile" + AdapterMail = "stmp" + AdapterConn = "conn" + AdaterEs = "es" +) + // Legacy loglevel constants to ensure backwards compatibility. // // Deprecated: will be removed in 1.5.0. @@ -94,6 +105,7 @@ func Register(name string, log loggerType) { type BeeLogger struct { lock sync.Mutex level int + msgChanLen int64 enableFuncCallDepth bool loggerFuncCallDepth int asynchronous bool @@ -119,11 +131,14 @@ var logMsgPool *sync.Pool // NewLogger returns a new BeeLogger. // channelLen means the number of messages in chan(used where asynchronous is true). // if the buffering chan is full, logger adapters write to file or other way. -func NewLogger(channelLen int64) *BeeLogger { +func NewLogger(channelLens ...int64) *BeeLogger { bl := new(BeeLogger) bl.level = LevelDebug bl.loggerFuncCallDepth = 2 - bl.msgChan = make(chan *logMsg, channelLen) + bl.msgChanLen = append(channelLens, 0)[0] + if bl.msgChanLen < 0 { + bl.msgChanLen = 0 + } bl.signalChan = make(chan string, 1) return bl } @@ -131,6 +146,7 @@ func NewLogger(channelLen int64) *BeeLogger { // Async set the log to asynchronous and start the goroutine func (bl *BeeLogger) Async() *BeeLogger { bl.asynchronous = true + bl.msgChan = make(chan *logMsg, bl.msgChanLen) logMsgPool = &sync.Pool{ New: func() interface{} { return &logMsg{} @@ -143,7 +159,8 @@ func (bl *BeeLogger) Async() *BeeLogger { // SetLogger provides a given logger adapter into BeeLogger with config string. // config need to be correct JSON as string: {"interval":360}. -func (bl *BeeLogger) SetLogger(adapterName string, config string) error { +func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { + config := append(configs, "{}")[0] bl.lock.Lock() defer bl.lock.Unlock() @@ -402,6 +419,7 @@ func (bl *BeeLogger) Close() { if bl.asynchronous { bl.signalChan <- "close" bl.wg.Wait() + close(bl.msgChan) } else { bl.flush() for _, l := range bl.outputs { @@ -409,7 +427,6 @@ func (bl *BeeLogger) Close() { } bl.outputs = nil } - close(bl.msgChan) close(bl.signalChan) } @@ -423,16 +440,155 @@ func (bl *BeeLogger) Reset() { } func (bl *BeeLogger) flush() { - for { - if len(bl.msgChan) > 0 { - bm := <-bl.msgChan - bl.writeToLoggers(bm.when, bm.msg, bm.level) - logMsgPool.Put(bm) - continue + if bl.asynchronous { + for { + if len(bl.msgChan) > 0 { + bm := <-bl.msgChan + bl.writeToLoggers(bm.when, bm.msg, bm.level) + logMsgPool.Put(bm) + continue + } + break } - break } for _, l := range bl.outputs { l.Flush() } } + +// BeeLogger references the used application logger. +var beeLogger = NewLogger(100) + +// GetLogger returns the default BeeLogger +func GetBeeLogger() *BeeLogger { + return beeLogger +} + +var beeLoggerMap = struct { + sync.RWMutex + logs map[string]*log.Logger +}{ + logs: map[string]*log.Logger{}, +} + +// GetLogger returns the default BeeLogger +func GetLogger(prefixes ...string) *log.Logger { + prefix := append(prefixes, "")[0] + if prefix != "" { + prefix = fmt.Sprintf(`[%s] `, prefix) + } + beeLoggerMap.RLock() + l, ok := beeLoggerMap.logs[prefix] + if ok { + beeLoggerMap.RUnlock() + return l + } + beeLoggerMap.RUnlock() + beeLoggerMap.Lock() + defer beeLoggerMap.Unlock() + l, ok = beeLoggerMap.logs[prefix] + if !ok { + l = log.New(beeLogger, prefix, 0) + beeLoggerMap.logs[prefix] = l + } + return l +} + +// Reset will remove all the adapter +func Reset() { + beeLogger.Reset() +} + +// SetLevel sets the global log level used by the simple logger. +func SetLevel(l int) { + beeLogger.SetLevel(l) +} + +// SetLogFuncCall set the CallDepth, default is 3 +func SetLogFuncCall(b bool) { + beeLogger.EnableFuncCallDepth(b) + beeLogger.SetLogFuncCallDepth(3) +} + +// SetLogger sets a new logger. +func SetLogger(adaptername string, config string) error { + err := beeLogger.SetLogger(adaptername, config) + if err != nil { + return err + } + return nil +} + +// Emergency logs a message at emergency level. +func Emergency(f interface{}, v ...interface{}) { + beeLogger.Emergency(logf(f, v...)) +} + +// Alert logs a message at alert level. +func Alert(f interface{}, v ...interface{}) { + beeLogger.Alert(logf(f, v...)) +} + +// Critical logs a message at critical level. +func Critical(f interface{}, v ...interface{}) { + beeLogger.Critical(logf(f, v...)) +} + +// Error logs a message at error level. +func Error(f interface{}, v ...interface{}) { + beeLogger.Error(logf(f, v...)) +} + +// Warning logs a message at warning level. +func Warning(f interface{}, v ...interface{}) { + beeLogger.Warning(logf(f, v...)) +} + +// Warn compatibility alias for Warning() +func Warn(f interface{}, v ...interface{}) { + beeLogger.Warn(logf(f, v...)) +} + +// Notice logs a message at notice level. +func Notice(f interface{}, v ...interface{}) { + beeLogger.Notice(logf(f, v...)) +} + +// Informational logs a message at info level. +func Informational(f interface{}, v ...interface{}) { + beeLogger.Informational(logf(f, v...)) +} + +// Info compatibility alias for Warning() +func Info(f interface{}, v ...interface{}) { + fmt.Print() + beeLogger.Info(logf(f, v...)) +} + +// Debug logs a message at debug level. +func Debug(f interface{}, v ...interface{}) { + beeLogger.Debug(logf(f, v...)) +} + +// Trace logs a message at trace level. +// compatibility alias for Warning() +func Trace(f interface{}, v ...interface{}) { + beeLogger.Trace(logf(f, v...)) +} + +func logf(f interface{}, v ...interface{}) string { + var msg string + switch f.(type) { + case string: + msg = f.(string) + if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") { + //format string + } else { + //do not contain format char + msg += strings.Repeat(" %v", len(v)) + } + default: + msg = fmt.Sprint(f) + strings.Repeat(" %v", len(v)) + } + return fmt.Sprintf(msg, v...) +} From 03840f3fe88cb9ca9f3c59045adfd730acc07564 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:38:26 +0800 Subject: [PATCH 02/20] give each of the adapter a neme --- logs/conn.go | 2 +- logs/console.go | 2 +- logs/es/es.go | 2 +- logs/file.go | 2 +- logs/multifile.go | 2 +- logs/smtp.go | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/logs/conn.go b/logs/conn.go index 1db1a427..6d5bf6bf 100644 --- a/logs/conn.go +++ b/logs/conn.go @@ -113,5 +113,5 @@ func (c *connWriter) needToConnectOnMsg() bool { } func init() { - Register("conn", NewConn) + Register(AdapterConn, NewConn) } diff --git a/logs/console.go b/logs/console.go index dc41dd7d..e6bf6c29 100644 --- a/logs/console.go +++ b/logs/console.go @@ -97,5 +97,5 @@ func (c *consoleWriter) Flush() { } func init() { - Register("console", NewConsole) + Register(AdapterConsole, NewConsole) } diff --git a/logs/es/es.go b/logs/es/es.go index 397ca2ef..ceebe71a 100644 --- a/logs/es/es.go +++ b/logs/es/es.go @@ -76,5 +76,5 @@ func (el *esLogger) Flush() { } func init() { - logs.Register("es", NewES) + logs.Register(logs.AdaterEs, NewES) } diff --git a/logs/file.go b/logs/file.go index 672823fa..159d4970 100644 --- a/logs/file.go +++ b/logs/file.go @@ -282,5 +282,5 @@ func (w *fileLogWriter) Flush() { } func init() { - Register("file", newFileWriter) + Register(AdapterFile, newFileWriter) } diff --git a/logs/multifile.go b/logs/multifile.go index b82ba274..63204e17 100644 --- a/logs/multifile.go +++ b/logs/multifile.go @@ -112,5 +112,5 @@ func newFilesWriter() Logger { } func init() { - Register("multifile", newFilesWriter) + Register(AdapterMultiFile, newFilesWriter) } diff --git a/logs/smtp.go b/logs/smtp.go index 47f5a0c6..834130ef 100644 --- a/logs/smtp.go +++ b/logs/smtp.go @@ -156,5 +156,5 @@ func (s *SMTPWriter) Destroy() { } func init() { - Register("smtp", newSMTPWriter) + Register(AdapterMail, newSMTPWriter) } From 98dfecfd8a0de2c6e2852bf019d7a01bc21b88cc Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:39:29 +0800 Subject: [PATCH 03/20] change beego log function to logs function --- admin.go | 5 ++- app.go | 28 ++++++------ config.go | 7 +-- hooks.go | 3 +- log.go | 116 -------------------------------------------------- parser.go | 5 ++- router.go | 17 ++++---- staticfile.go | 5 ++- template.go | 9 ++-- 9 files changed, 43 insertions(+), 152 deletions(-) delete mode 100644 log.go diff --git a/admin.go b/admin.go index cf5bc63a..94fa55b9 100644 --- a/admin.go +++ b/admin.go @@ -24,6 +24,7 @@ import ( "time" "github.com/astaxie/beego/grace" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/toolbox" "github.com/astaxie/beego/utils" ) @@ -410,7 +411,7 @@ func (admin *adminApp) Run() { for p, f := range admin.routers { http.Handle(p, f) } - BeeLogger.Info("Admin server Running on %s", addr) + logs.Info("Admin server Running on %s", addr) var err error if BConfig.Listen.Graceful { @@ -419,6 +420,6 @@ func (admin *adminApp) Run() { err = http.ListenAndServe(addr, nil) } if err != nil { - BeeLogger.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) + logs.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) } } diff --git a/app.go b/app.go index a065670a..77116a81 100644 --- a/app.go +++ b/app.go @@ -16,7 +16,6 @@ package beego import ( "fmt" - "log" "net" "net/http" "net/http/fcgi" @@ -25,6 +24,7 @@ import ( "time" "github.com/astaxie/beego/grace" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/utils" ) @@ -69,9 +69,9 @@ func (app *App) Run() { if BConfig.Listen.EnableFcgi { if BConfig.Listen.EnableStdIo { if err = fcgi.Serve(nil, app.Handlers); err == nil { // standard I/O - BeeLogger.Info("Use FCGI via standard I/O") + logs.Info("Use FCGI via standard I/O") } else { - BeeLogger.Critical("Cannot use FCGI via standard I/O", err) + logs.Critical("Cannot use FCGI via standard I/O", err) } return } @@ -85,10 +85,10 @@ func (app *App) Run() { l, err = net.Listen("tcp", addr) } if err != nil { - BeeLogger.Critical("Listen: ", err) + logs.Critical("Listen: ", err) } if err = fcgi.Serve(l, app.Handlers); err != nil { - BeeLogger.Critical("fcgi.Serve: ", err) + logs.Critical("fcgi.Serve: ", err) } return } @@ -96,7 +96,7 @@ func (app *App) Run() { app.Server.Handler = app.Handlers app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second app.Server.WriteTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second - app.Server.ErrorLog = log.New(BeeLogger, "", 0) + app.Server.ErrorLog = logs.GetLogger("HTTP") // run graceful mode if BConfig.Listen.Graceful { @@ -113,7 +113,7 @@ func (app *App) Run() { server.Server.ReadTimeout = app.Server.ReadTimeout server.Server.WriteTimeout = app.Server.WriteTimeout if err := server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil { - BeeLogger.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) + logs.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) time.Sleep(100 * time.Microsecond) endRunning <- true } @@ -128,7 +128,7 @@ func (app *App) Run() { server.Network = "tcp4" } if err := server.ListenAndServe(); err != nil { - BeeLogger.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) + logs.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) time.Sleep(100 * time.Microsecond) endRunning <- true } @@ -146,9 +146,9 @@ func (app *App) Run() { if BConfig.Listen.HTTPSPort != 0 { app.Server.Addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) } - BeeLogger.Info("https server Running on %s", app.Server.Addr) + logs.Info("https server Running on %s", app.Server.Addr) if err := app.Server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil { - BeeLogger.Critical("ListenAndServeTLS: ", err) + logs.Critical("ListenAndServeTLS: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true } @@ -157,24 +157,24 @@ func (app *App) Run() { if BConfig.Listen.EnableHTTP { go func() { app.Server.Addr = addr - BeeLogger.Info("http server Running on %s", app.Server.Addr) + logs.Info("http server Running on %s", app.Server.Addr) if BConfig.Listen.ListenTCP4 { ln, err := net.Listen("tcp4", app.Server.Addr) if err != nil { - BeeLogger.Critical("ListenAndServe: ", err) + logs.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true return } if err = app.Server.Serve(ln); err != nil { - BeeLogger.Critical("ListenAndServe: ", err) + logs.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true return } } else { if err := app.Server.ListenAndServe(); err != nil { - BeeLogger.Critical("ListenAndServe: ", err) + logs.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true } diff --git a/config.go b/config.go index f0316a62..72045fd3 100644 --- a/config.go +++ b/config.go @@ -21,6 +21,7 @@ import ( "strings" "github.com/astaxie/beego/config" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/session" "github.com/astaxie/beego/utils" ) @@ -293,14 +294,14 @@ func parseConfig(appConfigPath string) (err error) { } //init log - BeeLogger.Reset() + logs.Reset() for adaptor, config := range BConfig.Log.Outputs { - err = BeeLogger.SetLogger(adaptor, config) + err = logs.SetLogger(adaptor, config) if err != nil { fmt.Printf("%s with the config `%s` got err:%s\n", adaptor, config, err) } } - SetLogFuncCall(BConfig.Log.FileLineNum) + logs.SetLogFuncCall(BConfig.Log.FileLineNum) return nil } diff --git a/hooks.go b/hooks.go index 674f2858..3d784467 100644 --- a/hooks.go +++ b/hooks.go @@ -7,6 +7,7 @@ import ( "path/filepath" "github.com/astaxie/beego/context" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/session" ) @@ -71,7 +72,7 @@ func registerSession() error { func registerTemplate() error { if err := BuildTemplate(BConfig.WebConfig.ViewsPath); err != nil { if BConfig.RunMode == DEV { - Warn(err) + logs.Warn(err) } return err } diff --git a/log.go b/log.go deleted file mode 100644 index 46ec57dd..00000000 --- a/log.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "strings" - - "github.com/astaxie/beego/logs" -) - -// Log levels to control the logging output. -const ( - LevelEmergency = iota - LevelAlert - LevelCritical - LevelError - LevelWarning - LevelNotice - LevelInformational - LevelDebug -) - -// BeeLogger references the used application logger. -var BeeLogger = logs.NewLogger(100) - -// SetLevel sets the global log level used by the simple logger. -func SetLevel(l int) { - BeeLogger.SetLevel(l) -} - -// SetLogFuncCall set the CallDepth, default is 3 -func SetLogFuncCall(b bool) { - BeeLogger.EnableFuncCallDepth(b) - BeeLogger.SetLogFuncCallDepth(3) -} - -// SetLogger sets a new logger. -func SetLogger(adaptername string, config string) error { - err := BeeLogger.SetLogger(adaptername, config) - if err != nil { - return err - } - return nil -} - -// Emergency logs a message at emergency level. -func Emergency(v ...interface{}) { - BeeLogger.Emergency(generateFmtStr(len(v)), v...) -} - -// Alert logs a message at alert level. -func Alert(v ...interface{}) { - BeeLogger.Alert(generateFmtStr(len(v)), v...) -} - -// Critical logs a message at critical level. -func Critical(v ...interface{}) { - BeeLogger.Critical(generateFmtStr(len(v)), v...) -} - -// Error logs a message at error level. -func Error(v ...interface{}) { - BeeLogger.Error(generateFmtStr(len(v)), v...) -} - -// Warning logs a message at warning level. -func Warning(v ...interface{}) { - BeeLogger.Warning(generateFmtStr(len(v)), v...) -} - -// Warn compatibility alias for Warning() -func Warn(v ...interface{}) { - BeeLogger.Warn(generateFmtStr(len(v)), v...) -} - -// Notice logs a message at notice level. -func Notice(v ...interface{}) { - BeeLogger.Notice(generateFmtStr(len(v)), v...) -} - -// Informational logs a message at info level. -func Informational(v ...interface{}) { - BeeLogger.Informational(generateFmtStr(len(v)), v...) -} - -// Info compatibility alias for Warning() -func Info(v ...interface{}) { - BeeLogger.Info(generateFmtStr(len(v)), v...) -} - -// Debug logs a message at debug level. -func Debug(v ...interface{}) { - BeeLogger.Debug(generateFmtStr(len(v)), v...) -} - -// Trace logs a message at trace level. -// compatibility alias for Warning() -func Trace(v ...interface{}) { - BeeLogger.Trace(generateFmtStr(len(v)), v...) -} - -func generateFmtStr(n int) string { - return strings.Repeat("%v ", n) -} diff --git a/parser.go b/parser.go index 46d02320..24f7549b 100644 --- a/parser.go +++ b/parser.go @@ -27,6 +27,7 @@ import ( "sort" "strings" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/utils" ) @@ -58,7 +59,7 @@ func parserPkg(pkgRealpath, pkgpath string) error { rep := strings.NewReplacer("/", "_", ".", "_") commentFilename = coomentPrefix + rep.Replace(pkgpath) + ".go" if !compareFile(pkgRealpath) { - Info(pkgRealpath + " no changed") + logs.Info(pkgRealpath + " no changed") return nil } genInfoList = make(map[string][]ControllerComments) @@ -131,7 +132,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat func genRouterCode() { os.Mkdir(path.Join(AppPath, "routers"), 0755) - Info("generate router from comments") + logs.Info("generate router from comments") var ( globalinfo string sortKey []string diff --git a/router.go b/router.go index 5516ecda..960cd104 100644 --- a/router.go +++ b/router.go @@ -28,6 +28,7 @@ import ( "time" beecontext "github.com/astaxie/beego/context" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/toolbox" "github.com/astaxie/beego/utils" ) @@ -439,11 +440,11 @@ func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string { paths := strings.Split(endpoint, ".") if len(paths) <= 1 { - Warn("urlfor endpoint must like path.controller.method") + logs.Warn("urlfor endpoint must like path.controller.method") return "" } if len(values)%2 != 0 { - Warn("urlfor params must key-value pair") + logs.Warn("urlfor params must key-value pair") return "" } params := make(map[string]string) @@ -651,7 +652,7 @@ func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) var err error context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r) if err != nil { - Error(err) + logs.Error(err) exception("503", context) goto Admin } @@ -780,7 +781,7 @@ func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) if !context.ResponseWriter.Started && context.Output.Status == 0 { if BConfig.WebConfig.AutoRender { if err := execController.Render(); err != nil { - Error(err) + logs.Error(err) } } } @@ -825,7 +826,7 @@ Admin: devInfo = fmt.Sprintf("| % -10s | % -40s | % -16s | % -10s |", r.Method, r.URL.Path, timeDur.String(), "notmatch") } if DefaultAccessLogFilter == nil || !DefaultAccessLogFilter.Filter(context) { - Debug(devInfo) + logs.Debug(devInfo) } } @@ -850,14 +851,14 @@ func (p *ControllerRegister) recoverPanic(context *beecontext.Context) { } } var stack string - Critical("the request url is ", context.Input.URL()) - Critical("Handler crashed with error", err) + logs.Critical("the request url is ", context.Input.URL()) + logs.Critical("Handler crashed with error", err) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } - Critical(fmt.Sprintf("%s:%d", file, line)) + logs.Critical(fmt.Sprintf("%s:%d", file, line)) stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line)) } if BConfig.RunMode == DEV { diff --git a/staticfile.go b/staticfile.go index 1cd75b8c..8a1bc57b 100644 --- a/staticfile.go +++ b/staticfile.go @@ -27,6 +27,7 @@ import ( "time" "github.com/astaxie/beego/context" + "github.com/astaxie/beego/logs" ) var errNotStaticRequest = errors.New("request not a static file request") @@ -48,7 +49,7 @@ func serverStaticRouter(ctx *context.Context) { if filePath == "" || fileInfo == nil { if BConfig.RunMode == DEV { - Warn("Can't find/open the file:", filePath, err) + logs.Warn("Can't find/open the file:", filePath, err) } http.NotFound(ctx.ResponseWriter, ctx.Request) return @@ -72,7 +73,7 @@ func serverStaticRouter(ctx *context.Context) { b, n, sch, err := openFile(filePath, fileInfo, acceptEncoding) if err != nil { if BConfig.RunMode == DEV { - Warn("Can't compress the file:", filePath, err) + logs.Warn("Can't compress the file:", filePath, err) } http.NotFound(ctx.ResponseWriter, ctx.Request) return diff --git a/template.go b/template.go index e6c43f87..a7c719e8 100644 --- a/template.go +++ b/template.go @@ -26,6 +26,7 @@ import ( "strings" "sync" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/utils" ) @@ -46,7 +47,7 @@ func executeTemplate(wr io.Writer, name string, data interface{}) error { if t, ok := beeTemplates[name]; ok { err := t.ExecuteTemplate(wr, name, data) if err != nil { - Trace("template Execute err:", err) + logs.Trace("template Execute err:", err) } return err } @@ -162,7 +163,7 @@ func BuildTemplate(dir string, files ...string) error { templatesLock.Lock() t, err := getTemplate(self.root, file, v...) if err != nil { - Trace("parse template err:", file, err) + logs.Trace("parse template err:", file, err) } else { beeTemplates[file] = t } @@ -240,7 +241,7 @@ func _getTemplate(t0 *template.Template, root string, subMods [][]string, others var subMods1 [][]string t, subMods1, err = getTplDeep(root, otherFile, "", t) if err != nil { - Trace("template parse file err:", err) + logs.Trace("template parse file err:", err) } else if subMods1 != nil && len(subMods1) > 0 { t, err = _getTemplate(t, root, subMods1, others...) } @@ -261,7 +262,7 @@ func _getTemplate(t0 *template.Template, root string, subMods [][]string, others var subMods1 [][]string t, subMods1, err = getTplDeep(root, otherFile, "", t) if err != nil { - Trace("template parse file err:", err) + logs.Trace("template parse file err:", err) } else if subMods1 != nil && len(subMods1) > 0 { t, err = _getTemplate(t, root, subMods1, others...) } From cdfd830f659e210ec4ed3e70c72dedbef8ec8736 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:43:16 +0800 Subject: [PATCH 04/20] rename log format --- logs/log.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/logs/log.go b/logs/log.go index 1ec7dd1d..44bcfac1 100644 --- a/logs/log.go +++ b/logs/log.go @@ -521,62 +521,62 @@ func SetLogger(adaptername string, config string) error { // Emergency logs a message at emergency level. func Emergency(f interface{}, v ...interface{}) { - beeLogger.Emergency(logf(f, v...)) + beeLogger.Emergency(formatLog(f, v...)) } // Alert logs a message at alert level. func Alert(f interface{}, v ...interface{}) { - beeLogger.Alert(logf(f, v...)) + beeLogger.Alert(formatLog(f, v...)) } // Critical logs a message at critical level. func Critical(f interface{}, v ...interface{}) { - beeLogger.Critical(logf(f, v...)) + beeLogger.Critical(formatLog(f, v...)) } // Error logs a message at error level. func Error(f interface{}, v ...interface{}) { - beeLogger.Error(logf(f, v...)) + beeLogger.Error(formatLog(f, v...)) } // Warning logs a message at warning level. func Warning(f interface{}, v ...interface{}) { - beeLogger.Warning(logf(f, v...)) + beeLogger.Warning(formatLog(f, v...)) } // Warn compatibility alias for Warning() func Warn(f interface{}, v ...interface{}) { - beeLogger.Warn(logf(f, v...)) + beeLogger.Warn(formatLog(f, v...)) } // Notice logs a message at notice level. func Notice(f interface{}, v ...interface{}) { - beeLogger.Notice(logf(f, v...)) + beeLogger.Notice(formatLog(f, v...)) } // Informational logs a message at info level. func Informational(f interface{}, v ...interface{}) { - beeLogger.Informational(logf(f, v...)) + beeLogger.Informational(formatLog(f, v...)) } // Info compatibility alias for Warning() func Info(f interface{}, v ...interface{}) { fmt.Print() - beeLogger.Info(logf(f, v...)) + beeLogger.Info(formatLog(f, v...)) } // Debug logs a message at debug level. func Debug(f interface{}, v ...interface{}) { - beeLogger.Debug(logf(f, v...)) + beeLogger.Debug(formatLog(f, v...)) } // Trace logs a message at trace level. // compatibility alias for Warning() func Trace(f interface{}, v ...interface{}) { - beeLogger.Trace(logf(f, v...)) + beeLogger.Trace(formatLog(f, v...)) } -func logf(f interface{}, v ...interface{}) string { +func formatLog(f interface{}, v ...interface{}) string { var msg string switch f.(type) { case string: From a6c1377f91add359dd281405e2d7d297485f441e Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:43:45 +0800 Subject: [PATCH 05/20] change to 0 logger --- logs/log.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logs/log.go b/logs/log.go index 44bcfac1..cdd82a02 100644 --- a/logs/log.go +++ b/logs/log.go @@ -457,7 +457,7 @@ func (bl *BeeLogger) flush() { } // BeeLogger references the used application logger. -var beeLogger = NewLogger(100) +var beeLogger = NewLogger() // GetLogger returns the default BeeLogger func GetBeeLogger() *BeeLogger { From 0fb4a8af24a788c5d8ba9731ee5f19b9f5815214 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:46:52 +0800 Subject: [PATCH 06/20] function change --- logs/log.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/logs/log.go b/logs/log.go index cdd82a02..67bf2a73 100644 --- a/logs/log.go +++ b/logs/log.go @@ -511,8 +511,8 @@ func SetLogFuncCall(b bool) { } // SetLogger sets a new logger. -func SetLogger(adaptername string, config string) error { - err := beeLogger.SetLogger(adaptername, config) +func SetLogger(adapter string, config ...string) error { + err := beeLogger.SetLogger(adapter, config...) if err != nil { return err } From 8344a60552bd010385cc208157a215e6cb253705 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 17:49:39 +0800 Subject: [PATCH 07/20] add to upper case --- logs/log.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logs/log.go b/logs/log.go index 67bf2a73..7b65dbc3 100644 --- a/logs/log.go +++ b/logs/log.go @@ -475,7 +475,7 @@ var beeLoggerMap = struct { func GetLogger(prefixes ...string) *log.Logger { prefix := append(prefixes, "")[0] if prefix != "" { - prefix = fmt.Sprintf(`[%s] `, prefix) + prefix = fmt.Sprintf(`[%s] `, strings.ToUpper(prefix)) } beeLoggerMap.RLock() l, ok := beeLoggerMap.logs[prefix] From 0814eefa6293f21f487ebe3e3085b844435d9053 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 18:21:52 +0800 Subject: [PATCH 08/20] refactor writeMsg function --- logs/es/es.go | 2 +- logs/log.go | 20 +++++++++++++------- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/logs/es/es.go b/logs/es/es.go index ceebe71a..22f4f650 100644 --- a/logs/es/es.go +++ b/logs/es/es.go @@ -76,5 +76,5 @@ func (el *esLogger) Flush() { } func init() { - logs.Register(logs.AdaterEs, NewES) + logs.Register(logs.AdapterEs, NewES) } diff --git a/logs/log.go b/logs/log.go index 7b65dbc3..32e441f4 100644 --- a/logs/log.go +++ b/logs/log.go @@ -56,14 +56,16 @@ const ( LevelInformational LevelDebug ) +const levelCustom = -1 +// Name for adapter with beego official support const ( AdapterConsole = "console" AdapterFile = "file" AdapterMultiFile = "multifile" AdapterMail = "stmp" AdapterConn = "conn" - AdaterEs = "es" + AdapterEs = "es" ) // Legacy loglevel constants to ensure backwards compatibility. @@ -75,7 +77,7 @@ const ( LevelWarn = LevelWarning ) -type loggerType func() Logger +type newLoggerFunc func() Logger // Logger defines the behavior of a log provider. type Logger interface { @@ -85,12 +87,13 @@ type Logger interface { Flush() } -var adapters = make(map[string]loggerType) +var adapters = make(map[string]newLoggerFunc) +var levelPrefix = [LevelDebug + 1]string{"[M] ", "[A] ", "[C] ", "[E] ", "[W] ", "[N] ", "[I] ", "[D] "} // Register makes a log provide available by the provided name. // If Register is called twice with the same name or if driver is nil, // it panics. -func Register(name string, log loggerType) { +func Register(name string, log newLoggerFunc) { if log == nil { panic("logs: Register provide is nil") } @@ -222,14 +225,18 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) { p = p[0 : len(p)-1] } // set LevelCritical to ensure all log message will be write out - err = bl.writeMsg(LevelCritical, string(p)) + err = bl.writeMsg(levelCustom, string(p)) if err == nil { return len(p), err } return 0, err } -func (bl *BeeLogger) writeMsg(logLevel int, msg string) error { +func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error { + if logLevel != levelCustom { + msg = levelPrefix[logLevel] + msg + } + msg = fmt.Sprintf(msg, v...) when := time.Now() if bl.enableFuncCallDepth { _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) @@ -561,7 +568,6 @@ func Informational(f interface{}, v ...interface{}) { // Info compatibility alias for Warning() func Info(f interface{}, v ...interface{}) { - fmt.Print() beeLogger.Info(formatLog(f, v...)) } From d8bed89c442838ddcbfc75b6c1c645d5219c79ef Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 19:15:14 +0800 Subject: [PATCH 09/20] set console as default logger --- logs/log.go | 98 ++++++++++++++++++++++++++++------------------------- 1 file changed, 51 insertions(+), 47 deletions(-) diff --git a/logs/log.go b/logs/log.go index 32e441f4..0f5fa052 100644 --- a/logs/log.go +++ b/logs/log.go @@ -56,7 +56,10 @@ const ( LevelInformational LevelDebug ) -const levelCustom = -1 + +// levelLogLogger is defined to implement log.Logger +// the real log level will be LevelEmergency +const levelLoggerImpl = -1 // Name for adapter with beego official support const ( @@ -68,9 +71,7 @@ const ( AdapterEs = "es" ) -// Legacy loglevel constants to ensure backwards compatibility. -// -// Deprecated: will be removed in 1.5.0. +// Legacy log level constants to ensure backwards compatibility. const ( LevelInfo = LevelInformational LevelTrace = LevelDebug @@ -108,10 +109,11 @@ func Register(name string, log newLoggerFunc) { type BeeLogger struct { lock sync.Mutex level int - msgChanLen int64 + init bool enableFuncCallDepth bool loggerFuncCallDepth int asynchronous bool + msgChanLen int64 msgChan chan *logMsg signalChan chan string wg sync.WaitGroup @@ -143,11 +145,17 @@ func NewLogger(channelLens ...int64) *BeeLogger { bl.msgChanLen = 0 } bl.signalChan = make(chan string, 1) + bl.setLogger(AdapterConsole) return bl } // Async set the log to asynchronous and start the goroutine func (bl *BeeLogger) Async() *BeeLogger { + bl.lock.Lock() + defer bl.lock.Unlock() + if bl.asynchronous { + return bl + } bl.asynchronous = true bl.msgChan = make(chan *logMsg, bl.msgChanLen) logMsgPool = &sync.Pool{ @@ -162,11 +170,8 @@ func (bl *BeeLogger) Async() *BeeLogger { // SetLogger provides a given logger adapter into BeeLogger with config string. // config need to be correct JSON as string: {"interval":360}. -func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { +func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error { config := append(configs, "{}")[0] - bl.lock.Lock() - defer bl.lock.Unlock() - for _, l := range bl.outputs { if l.name == adapterName { return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName) @@ -188,6 +193,18 @@ func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { return nil } +// SetLogger provides a given logger adapter into BeeLogger with config string. +// config need to be correct JSON as string: {"interval":360}. +func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { + bl.lock.Lock() + defer bl.lock.Unlock() + if !bl.init { + bl.outputs = []*nameLogger{} + bl.init = true + } + return bl.setLogger(adapterName, configs...) +} + // DelLogger remove a logger adapter in BeeLogger. func (bl *BeeLogger) DelLogger(adapterName string) error { bl.lock.Lock() @@ -224,8 +241,8 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) { if p[len(p)-1] == '\n' { p = p[0 : len(p)-1] } - // set LevelCritical to ensure all log message will be write out - err = bl.writeMsg(levelCustom, string(p)) + // set levelLoggerImpl to ensure all log message will be write out + err = bl.writeMsg(levelLoggerImpl, string(p)) if err == nil { return len(p), err } @@ -233,7 +250,10 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) { } func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error { - if logLevel != levelCustom { + if logLevel == levelLoggerImpl { + // set to emergency to ensure all log will be print out correctly + logLevel = LevelEmergency + } else { msg = levelPrefix[logLevel] + msg } msg = fmt.Sprintf(msg, v...) @@ -313,8 +333,7 @@ func (bl *BeeLogger) Emergency(format string, v ...interface{}) { if LevelEmergency > bl.level { return } - msg := fmt.Sprintf("[M] "+format, v...) - bl.writeMsg(LevelEmergency, msg) + bl.writeMsg(LevelEmergency, format, v...) } // Alert Log ALERT level message. @@ -322,8 +341,7 @@ func (bl *BeeLogger) Alert(format string, v ...interface{}) { if LevelAlert > bl.level { return } - msg := fmt.Sprintf("[A] "+format, v...) - bl.writeMsg(LevelAlert, msg) + bl.writeMsg(LevelAlert, format, v...) } // Critical Log CRITICAL level message. @@ -331,8 +349,7 @@ func (bl *BeeLogger) Critical(format string, v ...interface{}) { if LevelCritical > bl.level { return } - msg := fmt.Sprintf("[C] "+format, v...) - bl.writeMsg(LevelCritical, msg) + bl.writeMsg(LevelCritical, format, v...) } // Error Log ERROR level message. @@ -340,17 +357,12 @@ func (bl *BeeLogger) Error(format string, v ...interface{}) { if LevelError > bl.level { return } - msg := fmt.Sprintf("[E] "+format, v...) - bl.writeMsg(LevelError, msg) + bl.writeMsg(LevelError, format, v...) } // Warning Log WARNING level message. func (bl *BeeLogger) Warning(format string, v ...interface{}) { - if LevelWarning > bl.level { - return - } - msg := fmt.Sprintf("[W] "+format, v...) - bl.writeMsg(LevelWarning, msg) + bl.Warn(format, v...) } // Notice Log NOTICE level message. @@ -358,17 +370,12 @@ func (bl *BeeLogger) Notice(format string, v ...interface{}) { if LevelNotice > bl.level { return } - msg := fmt.Sprintf("[N] "+format, v...) - bl.writeMsg(LevelNotice, msg) + bl.writeMsg(LevelNotice, format, v...) } // Informational Log INFORMATIONAL level message. func (bl *BeeLogger) Informational(format string, v ...interface{}) { - if LevelInformational > bl.level { - return - } - msg := fmt.Sprintf("[I] "+format, v...) - bl.writeMsg(LevelInformational, msg) + bl.Info(format, v...) } // Debug Log DEBUG level message. @@ -376,38 +383,31 @@ func (bl *BeeLogger) Debug(format string, v ...interface{}) { if LevelDebug > bl.level { return } - msg := fmt.Sprintf("[D] "+format, v...) - bl.writeMsg(LevelDebug, msg) + bl.writeMsg(LevelDebug, format, v...) } // Warn Log WARN level message. // compatibility alias for Warning() func (bl *BeeLogger) Warn(format string, v ...interface{}) { - if LevelWarning > bl.level { + if LevelWarn > bl.level { return } - msg := fmt.Sprintf("[W] "+format, v...) - bl.writeMsg(LevelWarning, msg) + bl.writeMsg(LevelWarn, format, v...) } // Info Log INFO level message. // compatibility alias for Informational() func (bl *BeeLogger) Info(format string, v ...interface{}) { - if LevelInformational > bl.level { + if LevelInfo > bl.level { return } - msg := fmt.Sprintf("[I] "+format, v...) - bl.writeMsg(LevelInformational, msg) + bl.writeMsg(LevelInfo, format, v...) } // Trace Log TRACE level message. // compatibility alias for Debug() func (bl *BeeLogger) Trace(format string, v ...interface{}) { - if LevelDebug > bl.level { - return - } - msg := fmt.Sprintf("[D] "+format, v...) - bl.writeMsg(LevelDebug, msg) + bl.Debug(format, v...) } // Flush flush all chan data. @@ -506,6 +506,10 @@ func Reset() { beeLogger.Reset() } +func Async() *BeeLogger { + return beeLogger.Async() +} + // SetLevel sets the global log level used by the simple logger. func SetLevel(l int) { beeLogger.SetLevel(l) @@ -548,7 +552,7 @@ func Error(f interface{}, v ...interface{}) { // Warning logs a message at warning level. func Warning(f interface{}, v ...interface{}) { - beeLogger.Warning(formatLog(f, v...)) + beeLogger.Warn(formatLog(f, v...)) } // Warn compatibility alias for Warning() @@ -563,7 +567,7 @@ func Notice(f interface{}, v ...interface{}) { // Informational logs a message at info level. func Informational(f interface{}, v ...interface{}) { - beeLogger.Informational(formatLog(f, v...)) + beeLogger.Info(formatLog(f, v...)) } // Info compatibility alias for Warning() From 06299fa47bf81f21a6989bf4a5819808b6c56b18 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 19:32:29 +0800 Subject: [PATCH 10/20] makes console as default logger --- logs/log.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/logs/log.go b/logs/log.go index 0f5fa052..cf0f6346 100644 --- a/logs/log.go +++ b/logs/log.go @@ -464,7 +464,11 @@ func (bl *BeeLogger) flush() { } // BeeLogger references the used application logger. -var beeLogger = NewLogger() +var beeLogger *BeeLogger + +func init() { + beeLogger = NewLogger() +} // GetLogger returns the default BeeLogger func GetBeeLogger() *BeeLogger { From f02ff0420d75a3d1d09e1e400e6bf0250848d6f7 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 20:22:42 +0800 Subject: [PATCH 11/20] no need to call Sprintf when no args --- logs/log.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/logs/log.go b/logs/log.go index cf0f6346..3d4a4d60 100644 --- a/logs/log.go +++ b/logs/log.go @@ -256,7 +256,9 @@ func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error } else { msg = levelPrefix[logLevel] + msg } - msg = fmt.Sprintf(msg, v...) + if len(v) > 0 { + msg = fmt.Sprintf(msg, v...) + } when := time.Now() if bl.enableFuncCallDepth { _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) From 52a0b657b7764530178ac36ca22af8df24e921e4 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Thu, 24 Mar 2016 20:27:00 +0800 Subject: [PATCH 12/20] for better performance --- logs/log.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/logs/log.go b/logs/log.go index 3d4a4d60..506e712d 100644 --- a/logs/log.go +++ b/logs/log.go @@ -597,6 +597,9 @@ func formatLog(f interface{}, v ...interface{}) string { switch f.(type) { case string: msg = f.(string) + if len(v) == 0 { + return msg + } if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") { //format string } else { @@ -604,7 +607,11 @@ func formatLog(f interface{}, v ...interface{}) string { msg += strings.Repeat(" %v", len(v)) } default: - msg = fmt.Sprint(f) + strings.Repeat(" %v", len(v)) + msg = fmt.Sprint(f) + if len(v) == 0 { + return msg + } + msg += strings.Repeat(" %v", len(v)) } return fmt.Sprintf(msg, v...) } From 94bde3a77768f6285b852240d8669f37a86d7966 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 10:31:48 +0800 Subject: [PATCH 13/20] change to logs --- filter_test.go | 6 ------ router_test.go | 11 ++++++----- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/filter_test.go b/filter_test.go index d9928d8d..4ca4d2b8 100644 --- a/filter_test.go +++ b/filter_test.go @@ -20,14 +20,8 @@ import ( "testing" "github.com/astaxie/beego/context" - "github.com/astaxie/beego/logs" ) -func init() { - BeeLogger = logs.NewLogger(10000) - BeeLogger.SetLogger("console", "") -} - var FilterUser = func(ctx *context.Context) { ctx.Output.Body([]byte("i am " + ctx.Input.Param(":last") + ctx.Input.Param(":first"))) } diff --git a/router_test.go b/router_test.go index f26f0c86..9f11286c 100644 --- a/router_test.go +++ b/router_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/astaxie/beego/context" + "github.com/astaxie/beego/logs" ) type TestController struct { @@ -94,7 +95,7 @@ func TestUrlFor(t *testing.T) { handler.Add("/api/list", &TestController{}, "*:List") handler.Add("/person/:last/:first", &TestController{}, "*:Param") if a := handler.URLFor("TestController.List"); a != "/api/list" { - Info(a) + logs.Info(a) t.Errorf("TestController.List must equal to /api/list") } if a := handler.URLFor("TestController.Param", ":last", "xie", ":first", "asta"); a != "/person/xie/asta" { @@ -120,24 +121,24 @@ func TestUrlFor2(t *testing.T) { handler.Add("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", &TestController{}, "*:Param") handler.Add("/:year:int/:month:int/:title/:entid", &TestController{}) if handler.URLFor("TestController.GetURL", ":username", "astaxie") != "/v1/astaxie/edit" { - Info(handler.URLFor("TestController.GetURL")) + logs.Info(handler.URLFor("TestController.GetURL")) t.Errorf("TestController.List must equal to /v1/astaxie/edit") } if handler.URLFor("TestController.List", ":v", "za", ":id", "12", ":page", "123") != "/v1/za/cms_12_123.html" { - Info(handler.URLFor("TestController.List")) + logs.Info(handler.URLFor("TestController.List")) t.Errorf("TestController.List must equal to /v1/za/cms_12_123.html") } if handler.URLFor("TestController.Param", ":v", "za", ":id", "12", ":page", "123") != "/v1/za_cms/ttt_12_123.html" { - Info(handler.URLFor("TestController.Param")) + logs.Info(handler.URLFor("TestController.Param")) t.Errorf("TestController.List must equal to /v1/za_cms/ttt_12_123.html") } if handler.URLFor("TestController.Get", ":year", "1111", ":month", "11", ":title", "aaaa", ":entid", "aaaa") != "/1111/11/aaaa/aaaa" { - Info(handler.URLFor("TestController.Get")) + logs.Info(handler.URLFor("TestController.Get")) t.Errorf("TestController.Get must equal to /1111/11/aaaa/aaaa") } } From 2db8c753fd3fa8c28d134a74fd0002a63841f52f Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 10:56:15 +0800 Subject: [PATCH 14/20] bee fix --- cache/cache_test.go | 14 +++++++------- cache/memcache/memcache_test.go | 8 ++++---- cache/redis/redis_test.go | 8 ++++---- cache/ssdb/ssdb_test.go | 8 ++++---- context/input_test.go | 2 +- migration/migration.go | 34 ++++++++++++++++----------------- utils/captcha/captcha.go | 7 ++++--- utils/pagination/controller.go | 2 +- 8 files changed, 42 insertions(+), 41 deletions(-) diff --git a/cache/cache_test.go b/cache/cache_test.go index 9ceb606a..40a9d60a 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -26,7 +26,7 @@ func TestCache(t *testing.T) { t.Error("init err") } timeoutDuration := 10 * time.Second - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -43,7 +43,7 @@ func TestCache(t *testing.T) { t.Error("check err") } - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } @@ -68,7 +68,7 @@ func TestCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -78,7 +78,7 @@ func TestCache(t *testing.T) { t.Error("get err") } - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { @@ -103,7 +103,7 @@ func TestFileCache(t *testing.T) { t.Error("init err") } timeoutDuration := 10 * time.Second - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -135,7 +135,7 @@ func TestFileCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -146,7 +146,7 @@ func TestFileCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/memcache/memcache_test.go b/cache/memcache/memcache_test.go index 0c8c57f2..ce16f066 100644 --- a/cache/memcache/memcache_test.go +++ b/cache/memcache/memcache_test.go @@ -30,7 +30,7 @@ func TestMemcacheCache(t *testing.T) { t.Error("init err") } timeoutDuration := 10 * time.Second - if err = bm.Put("astaxie", "1", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -42,7 +42,7 @@ func TestMemcacheCache(t *testing.T) { if bm.IsExist("astaxie") { t.Error("check err") } - if err = bm.Put("astaxie", "1", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } @@ -71,7 +71,7 @@ func TestMemcacheCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -83,7 +83,7 @@ func TestMemcacheCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/redis/redis_test.go b/cache/redis/redis_test.go index 47c5acc6..1fcba81d 100644 --- a/cache/redis/redis_test.go +++ b/cache/redis/redis_test.go @@ -29,7 +29,7 @@ func TestRedisCache(t *testing.T) { t.Error("init err") } timeoutDuration := 10 * time.Second - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -41,7 +41,7 @@ func TestRedisCache(t *testing.T) { if bm.IsExist("astaxie") { t.Error("check err") } - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } @@ -70,7 +70,7 @@ func TestRedisCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -82,7 +82,7 @@ func TestRedisCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/ssdb/ssdb_test.go b/cache/ssdb/ssdb_test.go index e03ba343..c389a357 100644 --- a/cache/ssdb/ssdb_test.go +++ b/cache/ssdb/ssdb_test.go @@ -19,7 +19,7 @@ func TestSsdbcacheCache(t *testing.T) { } timeoutDuration := 10 * time.Second //timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { + if err = ssdb.Put("ssdb", "ssdb", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if !ssdb.IsExist("ssdb") { @@ -27,7 +27,7 @@ func TestSsdbcacheCache(t *testing.T) { } // Get test done - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { + if err = ssdb.Put("ssdb", "ssdb", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } @@ -36,7 +36,7 @@ func TestSsdbcacheCache(t *testing.T) { } //inc/dec test done - if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil { + if err = ssdb.Put("ssdb", "2", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if err = ssdb.Incr("ssdb"); err != nil { @@ -52,7 +52,7 @@ func TestSsdbcacheCache(t *testing.T) { } // test del - if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil { + if err = ssdb.Put("ssdb", "3", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 { diff --git a/context/input_test.go b/context/input_test.go index 24f6fd99..8887aec4 100644 --- a/context/input_test.go +++ b/context/input_test.go @@ -100,7 +100,7 @@ func TestSubDomain(t *testing.T) { /* TODO Fix this r, _ = http.NewRequest("GET", "http://127.0.0.1/", nil) - beegoInput.Request = r + beegoInput.Context.Request = r if beegoInput.SubDomains() != "" { t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains()) } diff --git a/migration/migration.go b/migration/migration.go index 1591bc50..c9ca1bc6 100644 --- a/migration/migration.go +++ b/migration/migration.go @@ -33,7 +33,7 @@ import ( "strings" "time" - "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" ) @@ -90,7 +90,7 @@ func (m *Migration) Reset() { func (m *Migration) Exec(name, status string) error { o := orm.NewOrm() for _, s := range m.sqls { - beego.Info("exec sql:", s) + logs.Info("exec sql:", s) r := o.Raw(s) _, err := r.Exec() if err != nil { @@ -144,20 +144,20 @@ func Upgrade(lasttime int64) error { i := 0 for _, v := range sm { if v.created > lasttime { - beego.Info("start upgrade", v.name) + logs.Info("start upgrade", v.name) v.m.Reset() v.m.Up() err := v.m.Exec(v.name, "up") if err != nil { - beego.Error("execute error:", err) + logs.Error("execute error:", err) time.Sleep(2 * time.Second) return err } - beego.Info("end upgrade:", v.name) + logs.Info("end upgrade:", v.name) i++ } } - beego.Info("total success upgrade:", i, " migration") + logs.Info("total success upgrade:", i, " migration") time.Sleep(2 * time.Second) return nil } @@ -165,20 +165,20 @@ func Upgrade(lasttime int64) error { // Rollback rollback the migration by the name func Rollback(name string) error { if v, ok := migrationMap[name]; ok { - beego.Info("start rollback") + logs.Info("start rollback") v.Reset() v.Down() err := v.Exec(name, "down") if err != nil { - beego.Error("execute error:", err) + logs.Error("execute error:", err) time.Sleep(2 * time.Second) return err } - beego.Info("end rollback") + logs.Info("end rollback") time.Sleep(2 * time.Second) return nil } - beego.Error("not exist the migrationMap name:" + name) + logs.Error("not exist the migrationMap name:" + name) time.Sleep(2 * time.Second) return errors.New("not exist the migrationMap name:" + name) } @@ -191,23 +191,23 @@ func Reset() error { for j := len(sm) - 1; j >= 0; j-- { v := sm[j] if isRollBack(v.name) { - beego.Info("skip the", v.name) + logs.Info("skip the", v.name) time.Sleep(1 * time.Second) continue } - beego.Info("start reset:", v.name) + logs.Info("start reset:", v.name) v.m.Reset() v.m.Down() err := v.m.Exec(v.name, "down") if err != nil { - beego.Error("execute error:", err) + logs.Error("execute error:", err) time.Sleep(2 * time.Second) return err } i++ - beego.Info("end reset:", v.name) + logs.Info("end reset:", v.name) } - beego.Info("total success reset:", i, " migration") + logs.Info("total success reset:", i, " migration") time.Sleep(2 * time.Second) return nil } @@ -216,7 +216,7 @@ func Reset() error { func Refresh() error { err := Reset() if err != nil { - beego.Error("execute error:", err) + logs.Error("execute error:", err) time.Sleep(2 * time.Second) return err } @@ -265,7 +265,7 @@ func isRollBack(name string) bool { var maps []orm.Params num, err := o.Raw("select * from migrations where `name` = ? order by id_migration desc", name).Values(&maps) if err != nil { - beego.Info("get name has error", err) + logs.Info("get name has error", err) return false } if num <= 0 { diff --git a/utils/captcha/captcha.go b/utils/captcha/captcha.go index 1a4a6edc..42ac70d3 100644 --- a/utils/captcha/captcha.go +++ b/utils/captcha/captcha.go @@ -69,6 +69,7 @@ import ( "github.com/astaxie/beego" "github.com/astaxie/beego/cache" "github.com/astaxie/beego/context" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/utils" ) @@ -139,7 +140,7 @@ func (c *Captcha) Handler(ctx *context.Context) { if err := c.store.Put(key, chars, c.Expiration); err != nil { ctx.Output.SetStatus(500) ctx.WriteString("captcha reload error") - beego.Error("Reload Create Captcha Error:", err) + logs.Error("Reload Create Captcha Error:", err) return } } else { @@ -154,7 +155,7 @@ func (c *Captcha) Handler(ctx *context.Context) { img := NewImage(chars, c.StdWidth, c.StdHeight) if _, err := img.WriteTo(ctx.ResponseWriter); err != nil { - beego.Error("Write Captcha Image Error:", err) + logs.Error("Write Captcha Image Error:", err) } } @@ -162,7 +163,7 @@ func (c *Captcha) Handler(ctx *context.Context) { func (c *Captcha) CreateCaptchaHTML() template.HTML { value, err := c.CreateCaptcha() if err != nil { - beego.Error("Create Captcha Error:", err) + logs.Error("Create Captcha Error:", err) return "" } diff --git a/utils/pagination/controller.go b/utils/pagination/controller.go index 1d99cac5..2f022d0c 100644 --- a/utils/pagination/controller.go +++ b/utils/pagination/controller.go @@ -18,7 +18,7 @@ import ( "github.com/astaxie/beego/context" ) -// SetPaginator Instantiates a Paginator and assigns it to context.Input.Data["paginator"]. +// SetPaginator Instantiates a Paginator and assigns it to context.Input.Data("paginator"). func SetPaginator(context *context.Context, per int, nums int64) (paginator *Paginator) { paginator = NewPaginator(context.Request, per, nums) context.Input.SetData("paginator", &paginator) From 6d0fe8c4f44ff2e89d4d8c00b4e1931e96eb395b Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 11:05:20 +0800 Subject: [PATCH 15/20] go fmt cache file --- cache/redis/redis_test.go | 1 - cache/ssdb/ssdb_test.go | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cache/redis/redis_test.go b/cache/redis/redis_test.go index 1fcba81d..e7aa78cb 100644 --- a/cache/redis/redis_test.go +++ b/cache/redis/redis_test.go @@ -19,7 +19,6 @@ import ( "time" "github.com/garyburd/redigo/redis" - "github.com/astaxie/beego/cache" ) diff --git a/cache/ssdb/ssdb_test.go b/cache/ssdb/ssdb_test.go index c389a357..8083f52d 100644 --- a/cache/ssdb/ssdb_test.go +++ b/cache/ssdb/ssdb_test.go @@ -1,10 +1,11 @@ package ssdb import ( - "github.com/astaxie/beego/cache" "strconv" "testing" "time" + + "github.com/astaxie/beego/cache" ) func TestSsdbcacheCache(t *testing.T) { From 850dc59b6e2610a589b3fd11c48b5b857c42a57a Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 11:13:39 +0800 Subject: [PATCH 16/20] should remove when 2.0 is released --- log.go | 108 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 log.go diff --git a/log.go b/log.go new file mode 100644 index 00000000..214f6d14 --- /dev/null +++ b/log.go @@ -0,0 +1,108 @@ +// Copyright 2014 beego Author. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package beego + +import ( + "strings" + + "github.com/astaxie/beego/logs" +) + +// Log levels to control the logging output. +const ( + LevelEmergency = iota + LevelAlert + LevelCritical + LevelError + LevelWarning + LevelNotice + LevelInformational + LevelDebug +) + +// SetLevel sets the global log level used by the simple logger. +func SetLevel(l int) { + logs.SetLevel(l) +} + +// SetLogFuncCall set the CallDepth, default is 3 +func SetLogFuncCall(b bool) { + logs.SetLogFuncCall(b) +} + +// SetLogger sets a new logger. +func SetLogger(adaptername string, config string) error { + return logs.SetLogger(adaptername, config) +} + +// Emergency logs a message at emergency level. +func Emergency(v ...interface{}) { + logs.Emergency(generateFmtStr(len(v)), v...) +} + +// Alert logs a message at alert level. +func Alert(v ...interface{}) { + logs.Alert(generateFmtStr(len(v)), v...) +} + +// Critical logs a message at critical level. +func Critical(v ...interface{}) { + logs.Critical(generateFmtStr(len(v)), v...) +} + +// Error logs a message at error level. +func Error(v ...interface{}) { + logs.Error(generateFmtStr(len(v)), v...) +} + +// Warning logs a message at warning level. +func Warning(v ...interface{}) { + logs.Warning(generateFmtStr(len(v)), v...) +} + +// Warn compatibility alias for Warning() +func Warn(v ...interface{}) { + logs.Warn(generateFmtStr(len(v)), v...) +} + +// Notice logs a message at notice level. +func Notice(v ...interface{}) { + logs.Notice(generateFmtStr(len(v)), v...) +} + +// Informational logs a message at info level. +func Informational(v ...interface{}) { + logs.Informational(generateFmtStr(len(v)), v...) +} + +// Info compatibility alias for Warning() +func Info(v ...interface{}) { + logs.Info(generateFmtStr(len(v)), v...) +} + +// Debug logs a message at debug level. +func Debug(v ...interface{}) { + logs.Debug(generateFmtStr(len(v)), v...) +} + +// Trace logs a message at trace level. +// compatibility alias for Warning() +func Trace(v ...interface{}) { + logs.Trace(generateFmtStr(len(v)), v...) +} + +func generateFmtStr(n int) string { + return strings.Repeat("%v ", n) +} From fa4a231cd4248e80a08ef7965be0b0c421bf8784 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 11:46:19 +0800 Subject: [PATCH 17/20] duration change to second --- cache/cache_test.go | 4 ++-- cache/memcache/memcache_test.go | 2 +- cache/redis/redis_test.go | 4 ++-- cache/ssdb/ssdb_test.go | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cache/cache_test.go b/cache/cache_test.go index 40a9d60a..ec344cb1 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -25,7 +25,7 @@ func TestCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 10 if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } @@ -102,7 +102,7 @@ func TestFileCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 10 if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } diff --git a/cache/memcache/memcache_test.go b/cache/memcache/memcache_test.go index ce16f066..9b9582f7 100644 --- a/cache/memcache/memcache_test.go +++ b/cache/memcache/memcache_test.go @@ -29,7 +29,7 @@ func TestMemcacheCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 10 if err = bm.Put("astaxie", "1", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } diff --git a/cache/redis/redis_test.go b/cache/redis/redis_test.go index e7aa78cb..91efbb3e 100644 --- a/cache/redis/redis_test.go +++ b/cache/redis/redis_test.go @@ -18,8 +18,8 @@ import ( "testing" "time" - "github.com/garyburd/redigo/redis" "github.com/astaxie/beego/cache" + "github.com/garyburd/redigo/redis" ) func TestRedisCache(t *testing.T) { @@ -27,7 +27,7 @@ func TestRedisCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 10 if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { t.Error("set Error", err) } diff --git a/cache/ssdb/ssdb_test.go b/cache/ssdb/ssdb_test.go index 8083f52d..4fea6fd8 100644 --- a/cache/ssdb/ssdb_test.go +++ b/cache/ssdb/ssdb_test.go @@ -18,7 +18,7 @@ func TestSsdbcacheCache(t *testing.T) { if ssdb.IsExist("ssdb") { t.Error("check err") } - timeoutDuration := 10 * time.Second + timeoutDuration := 10 //timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent if err = ssdb.Put("ssdb", "ssdb", timeoutDuration*time.Second); err != nil { t.Error("set Error", err) From e59271662cb815ad644e92a50c81ed38bdb7be8a Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 13:25:29 +0800 Subject: [PATCH 18/20] fix bee fix --- cache/cache_test.go | 18 +++++++++--------- cache/memcache/memcache_test.go | 10 +++++----- cache/redis/redis_test.go | 10 +++++----- cache/ssdb/ssdb_test.go | 10 +++++----- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/cache/cache_test.go b/cache/cache_test.go index ec344cb1..9ceb606a 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -25,8 +25,8 @@ func TestCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 - if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { + timeoutDuration := 10 * time.Second + if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -43,7 +43,7 @@ func TestCache(t *testing.T) { t.Error("check err") } - if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } @@ -68,7 +68,7 @@ func TestCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -78,7 +78,7 @@ func TestCache(t *testing.T) { t.Error("get err") } - if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { @@ -102,8 +102,8 @@ func TestFileCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 - if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { + timeoutDuration := 10 * time.Second + if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -135,7 +135,7 @@ func TestFileCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -146,7 +146,7 @@ func TestFileCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/memcache/memcache_test.go b/cache/memcache/memcache_test.go index 9b9582f7..0c8c57f2 100644 --- a/cache/memcache/memcache_test.go +++ b/cache/memcache/memcache_test.go @@ -29,8 +29,8 @@ func TestMemcacheCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 - if err = bm.Put("astaxie", "1", timeoutDuration*time.Second); err != nil { + timeoutDuration := 10 * time.Second + if err = bm.Put("astaxie", "1", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -42,7 +42,7 @@ func TestMemcacheCache(t *testing.T) { if bm.IsExist("astaxie") { t.Error("check err") } - if err = bm.Put("astaxie", "1", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", "1", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -71,7 +71,7 @@ func TestMemcacheCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -83,7 +83,7 @@ func TestMemcacheCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/redis/redis_test.go b/cache/redis/redis_test.go index 91efbb3e..6b81da4d 100644 --- a/cache/redis/redis_test.go +++ b/cache/redis/redis_test.go @@ -27,8 +27,8 @@ func TestRedisCache(t *testing.T) { if err != nil { t.Error("init err") } - timeoutDuration := 10 - if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { + timeoutDuration := 10 * time.Second + if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -40,7 +40,7 @@ func TestRedisCache(t *testing.T) { if bm.IsExist("astaxie") { t.Error("check err") } - if err = bm.Put("astaxie", 1, timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { t.Error("set Error", err) } @@ -69,7 +69,7 @@ func TestRedisCache(t *testing.T) { } //test string - if err = bm.Put("astaxie", "author", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie") { @@ -81,7 +81,7 @@ func TestRedisCache(t *testing.T) { } //test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration*time.Second); err != nil { + if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { t.Error("set Error", err) } if !bm.IsExist("astaxie1") { diff --git a/cache/ssdb/ssdb_test.go b/cache/ssdb/ssdb_test.go index 4fea6fd8..dd474960 100644 --- a/cache/ssdb/ssdb_test.go +++ b/cache/ssdb/ssdb_test.go @@ -18,9 +18,9 @@ func TestSsdbcacheCache(t *testing.T) { if ssdb.IsExist("ssdb") { t.Error("check err") } - timeoutDuration := 10 + timeoutDuration := 10 * time.Second //timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration*time.Second); err != nil { + if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { t.Error("set Error", err) } if !ssdb.IsExist("ssdb") { @@ -28,7 +28,7 @@ func TestSsdbcacheCache(t *testing.T) { } // Get test done - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration*time.Second); err != nil { + if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { t.Error("set Error", err) } @@ -37,7 +37,7 @@ func TestSsdbcacheCache(t *testing.T) { } //inc/dec test done - if err = ssdb.Put("ssdb", "2", timeoutDuration*time.Second); err != nil { + if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil { t.Error("set Error", err) } if err = ssdb.Incr("ssdb"); err != nil { @@ -53,7 +53,7 @@ func TestSsdbcacheCache(t *testing.T) { } // test del - if err = ssdb.Put("ssdb", "3", timeoutDuration*time.Second); err != nil { + if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil { t.Error("set Error", err) } if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 { From 826f81f47951b568088dd709a0407d32474c7f5d Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 15:04:52 +0800 Subject: [PATCH 19/20] remove from init method --- log.go | 3 +++ logs/log.go | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/log.go b/log.go index 214f6d14..e9412f92 100644 --- a/log.go +++ b/log.go @@ -32,6 +32,9 @@ const ( LevelDebug ) +// BeeLogger references the used application logger. +var BeeLogger = logs.GetBeeLogger() + // SetLevel sets the global log level used by the simple logger. func SetLevel(l int) { logs.SetLevel(l) diff --git a/logs/log.go b/logs/log.go index 506e712d..11d54ef8 100644 --- a/logs/log.go +++ b/logs/log.go @@ -120,6 +120,8 @@ type BeeLogger struct { outputs []*nameLogger } +const defaultAsyncMsgLen = 1e3 + type nameLogger struct { Logger name string @@ -157,6 +159,9 @@ func (bl *BeeLogger) Async() *BeeLogger { return bl } bl.asynchronous = true + if bl.msgChanLen <= 0 { + bl.msgChanLen = defaultAsyncMsgLen + } bl.msgChan = make(chan *logMsg, bl.msgChanLen) logMsgPool = &sync.Pool{ New: func() interface{} { @@ -250,6 +255,11 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) { } func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error { + if !beeLogger.init { + bl.lock.Lock() + bl.setLogger(AdapterConsole) + bl.lock.Unlock() + } if logLevel == levelLoggerImpl { // set to emergency to ensure all log will be print out correctly logLevel = LevelEmergency @@ -465,12 +475,8 @@ func (bl *BeeLogger) flush() { } } -// BeeLogger references the used application logger. -var beeLogger *BeeLogger - -func init() { - beeLogger = NewLogger() -} +// beeLogger references the used application logger. +var beeLogger *BeeLogger = NewLogger() // GetLogger returns the default BeeLogger func GetBeeLogger() *BeeLogger { From 45f239012855c4b363dc07ab929ad021dfd97db7 Mon Sep 17 00:00:00 2001 From: JessonChan Date: Fri, 25 Mar 2016 15:13:28 +0800 Subject: [PATCH 20/20] logger changed --- logs/log.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/logs/log.go b/logs/log.go index 11d54ef8..107c3b20 100644 --- a/logs/log.go +++ b/logs/log.go @@ -143,8 +143,8 @@ func NewLogger(channelLens ...int64) *BeeLogger { bl.level = LevelDebug bl.loggerFuncCallDepth = 2 bl.msgChanLen = append(channelLens, 0)[0] - if bl.msgChanLen < 0 { - bl.msgChanLen = 0 + if bl.msgChanLen <= 0 { + bl.msgChanLen = defaultAsyncMsgLen } bl.signalChan = make(chan string, 1) bl.setLogger(AdapterConsole) @@ -159,9 +159,6 @@ func (bl *BeeLogger) Async() *BeeLogger { return bl } bl.asynchronous = true - if bl.msgChanLen <= 0 { - bl.msgChanLen = defaultAsyncMsgLen - } bl.msgChan = make(chan *logMsg, bl.msgChanLen) logMsgPool = &sync.Pool{ New: func() interface{} {