1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 20:00:55 +00:00

change beego log function to logs function

This commit is contained in:
JessonChan 2016-03-24 17:39:29 +08:00
parent 03840f3fe8
commit 98dfecfd8a
9 changed files with 43 additions and 152 deletions

View File

@ -24,6 +24,7 @@ import (
"time" "time"
"github.com/astaxie/beego/grace" "github.com/astaxie/beego/grace"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/toolbox" "github.com/astaxie/beego/toolbox"
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
@ -410,7 +411,7 @@ func (admin *adminApp) Run() {
for p, f := range admin.routers { for p, f := range admin.routers {
http.Handle(p, f) http.Handle(p, f)
} }
BeeLogger.Info("Admin server Running on %s", addr) logs.Info("Admin server Running on %s", addr)
var err error var err error
if BConfig.Listen.Graceful { if BConfig.Listen.Graceful {
@ -419,6 +420,6 @@ func (admin *adminApp) Run() {
err = http.ListenAndServe(addr, nil) err = http.ListenAndServe(addr, nil)
} }
if err != nil { if err != nil {
BeeLogger.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) logs.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
} }
} }

28
app.go
View File

@ -16,7 +16,6 @@ package beego
import ( import (
"fmt" "fmt"
"log"
"net" "net"
"net/http" "net/http"
"net/http/fcgi" "net/http/fcgi"
@ -25,6 +24,7 @@ import (
"time" "time"
"github.com/astaxie/beego/grace" "github.com/astaxie/beego/grace"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
@ -69,9 +69,9 @@ func (app *App) Run() {
if BConfig.Listen.EnableFcgi { if BConfig.Listen.EnableFcgi {
if BConfig.Listen.EnableStdIo { if BConfig.Listen.EnableStdIo {
if err = fcgi.Serve(nil, app.Handlers); err == nil { // standard I/O 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 { } else {
BeeLogger.Critical("Cannot use FCGI via standard I/O", err) logs.Critical("Cannot use FCGI via standard I/O", err)
} }
return return
} }
@ -85,10 +85,10 @@ func (app *App) Run() {
l, err = net.Listen("tcp", addr) l, err = net.Listen("tcp", addr)
} }
if err != nil { if err != nil {
BeeLogger.Critical("Listen: ", err) logs.Critical("Listen: ", err)
} }
if err = fcgi.Serve(l, app.Handlers); err != nil { if err = fcgi.Serve(l, app.Handlers); err != nil {
BeeLogger.Critical("fcgi.Serve: ", err) logs.Critical("fcgi.Serve: ", err)
} }
return return
} }
@ -96,7 +96,7 @@ func (app *App) Run() {
app.Server.Handler = app.Handlers app.Server.Handler = app.Handlers
app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second
app.Server.WriteTimeout = 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 // run graceful mode
if BConfig.Listen.Graceful { if BConfig.Listen.Graceful {
@ -113,7 +113,7 @@ func (app *App) Run() {
server.Server.ReadTimeout = app.Server.ReadTimeout server.Server.ReadTimeout = app.Server.ReadTimeout
server.Server.WriteTimeout = app.Server.WriteTimeout server.Server.WriteTimeout = app.Server.WriteTimeout
if err := server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil { 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) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
} }
@ -128,7 +128,7 @@ func (app *App) Run() {
server.Network = "tcp4" server.Network = "tcp4"
} }
if err := server.ListenAndServe(); err != nil { 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) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
} }
@ -146,9 +146,9 @@ func (app *App) Run() {
if BConfig.Listen.HTTPSPort != 0 { if BConfig.Listen.HTTPSPort != 0 {
app.Server.Addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) 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 { 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) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
} }
@ -157,24 +157,24 @@ func (app *App) Run() {
if BConfig.Listen.EnableHTTP { if BConfig.Listen.EnableHTTP {
go func() { go func() {
app.Server.Addr = addr 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 { if BConfig.Listen.ListenTCP4 {
ln, err := net.Listen("tcp4", app.Server.Addr) ln, err := net.Listen("tcp4", app.Server.Addr)
if err != nil { if err != nil {
BeeLogger.Critical("ListenAndServe: ", err) logs.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
return return
} }
if err = app.Server.Serve(ln); err != nil { if err = app.Server.Serve(ln); err != nil {
BeeLogger.Critical("ListenAndServe: ", err) logs.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
return return
} }
} else { } else {
if err := app.Server.ListenAndServe(); err != nil { if err := app.Server.ListenAndServe(); err != nil {
BeeLogger.Critical("ListenAndServe: ", err) logs.Critical("ListenAndServe: ", err)
time.Sleep(100 * time.Microsecond) time.Sleep(100 * time.Microsecond)
endRunning <- true endRunning <- true
} }

View File

@ -21,6 +21,7 @@ import (
"strings" "strings"
"github.com/astaxie/beego/config" "github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/session" "github.com/astaxie/beego/session"
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
@ -293,14 +294,14 @@ func parseConfig(appConfigPath string) (err error) {
} }
//init log //init log
BeeLogger.Reset() logs.Reset()
for adaptor, config := range BConfig.Log.Outputs { for adaptor, config := range BConfig.Log.Outputs {
err = BeeLogger.SetLogger(adaptor, config) err = logs.SetLogger(adaptor, config)
if err != nil { if err != nil {
fmt.Printf("%s with the config `%s` got err:%s\n", adaptor, config, err) 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 return nil
} }

View File

@ -7,6 +7,7 @@ import (
"path/filepath" "path/filepath"
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/session" "github.com/astaxie/beego/session"
) )
@ -71,7 +72,7 @@ func registerSession() error {
func registerTemplate() error { func registerTemplate() error {
if err := BuildTemplate(BConfig.WebConfig.ViewsPath); err != nil { if err := BuildTemplate(BConfig.WebConfig.ViewsPath); err != nil {
if BConfig.RunMode == DEV { if BConfig.RunMode == DEV {
Warn(err) logs.Warn(err)
} }
return err return err
} }

116
log.go
View File

@ -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)
}

View File

@ -27,6 +27,7 @@ import (
"sort" "sort"
"strings" "strings"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
@ -58,7 +59,7 @@ func parserPkg(pkgRealpath, pkgpath string) error {
rep := strings.NewReplacer("/", "_", ".", "_") rep := strings.NewReplacer("/", "_", ".", "_")
commentFilename = coomentPrefix + rep.Replace(pkgpath) + ".go" commentFilename = coomentPrefix + rep.Replace(pkgpath) + ".go"
if !compareFile(pkgRealpath) { if !compareFile(pkgRealpath) {
Info(pkgRealpath + " no changed") logs.Info(pkgRealpath + " no changed")
return nil return nil
} }
genInfoList = make(map[string][]ControllerComments) genInfoList = make(map[string][]ControllerComments)
@ -131,7 +132,7 @@ func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpat
func genRouterCode() { func genRouterCode() {
os.Mkdir(path.Join(AppPath, "routers"), 0755) os.Mkdir(path.Join(AppPath, "routers"), 0755)
Info("generate router from comments") logs.Info("generate router from comments")
var ( var (
globalinfo string globalinfo string
sortKey []string sortKey []string

View File

@ -28,6 +28,7 @@ import (
"time" "time"
beecontext "github.com/astaxie/beego/context" beecontext "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/toolbox" "github.com/astaxie/beego/toolbox"
"github.com/astaxie/beego/utils" "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 { func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string {
paths := strings.Split(endpoint, ".") paths := strings.Split(endpoint, ".")
if len(paths) <= 1 { if len(paths) <= 1 {
Warn("urlfor endpoint must like path.controller.method") logs.Warn("urlfor endpoint must like path.controller.method")
return "" return ""
} }
if len(values)%2 != 0 { if len(values)%2 != 0 {
Warn("urlfor params must key-value pair") logs.Warn("urlfor params must key-value pair")
return "" return ""
} }
params := make(map[string]string) params := make(map[string]string)
@ -651,7 +652,7 @@ func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request)
var err error var err error
context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r) context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r)
if err != nil { if err != nil {
Error(err) logs.Error(err)
exception("503", context) exception("503", context)
goto Admin 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 !context.ResponseWriter.Started && context.Output.Status == 0 {
if BConfig.WebConfig.AutoRender { if BConfig.WebConfig.AutoRender {
if err := execController.Render(); err != nil { 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") devInfo = fmt.Sprintf("| % -10s | % -40s | % -16s | % -10s |", r.Method, r.URL.Path, timeDur.String(), "notmatch")
} }
if DefaultAccessLogFilter == nil || !DefaultAccessLogFilter.Filter(context) { 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 var stack string
Critical("the request url is ", context.Input.URL()) logs.Critical("the request url is ", context.Input.URL())
Critical("Handler crashed with error", err) logs.Critical("Handler crashed with error", err)
for i := 1; ; i++ { for i := 1; ; i++ {
_, file, line, ok := runtime.Caller(i) _, file, line, ok := runtime.Caller(i)
if !ok { if !ok {
break 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)) stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
} }
if BConfig.RunMode == DEV { if BConfig.RunMode == DEV {

View File

@ -27,6 +27,7 @@ import (
"time" "time"
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
) )
var errNotStaticRequest = errors.New("request not a static file request") var errNotStaticRequest = errors.New("request not a static file request")
@ -48,7 +49,7 @@ func serverStaticRouter(ctx *context.Context) {
if filePath == "" || fileInfo == nil { if filePath == "" || fileInfo == nil {
if BConfig.RunMode == DEV { 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) http.NotFound(ctx.ResponseWriter, ctx.Request)
return return
@ -72,7 +73,7 @@ func serverStaticRouter(ctx *context.Context) {
b, n, sch, err := openFile(filePath, fileInfo, acceptEncoding) b, n, sch, err := openFile(filePath, fileInfo, acceptEncoding)
if err != nil { if err != nil {
if BConfig.RunMode == DEV { 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) http.NotFound(ctx.ResponseWriter, ctx.Request)
return return

View File

@ -26,6 +26,7 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/utils" "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 { if t, ok := beeTemplates[name]; ok {
err := t.ExecuteTemplate(wr, name, data) err := t.ExecuteTemplate(wr, name, data)
if err != nil { if err != nil {
Trace("template Execute err:", err) logs.Trace("template Execute err:", err)
} }
return err return err
} }
@ -162,7 +163,7 @@ func BuildTemplate(dir string, files ...string) error {
templatesLock.Lock() templatesLock.Lock()
t, err := getTemplate(self.root, file, v...) t, err := getTemplate(self.root, file, v...)
if err != nil { if err != nil {
Trace("parse template err:", file, err) logs.Trace("parse template err:", file, err)
} else { } else {
beeTemplates[file] = t beeTemplates[file] = t
} }
@ -240,7 +241,7 @@ func _getTemplate(t0 *template.Template, root string, subMods [][]string, others
var subMods1 [][]string var subMods1 [][]string
t, subMods1, err = getTplDeep(root, otherFile, "", t) t, subMods1, err = getTplDeep(root, otherFile, "", t)
if err != nil { if err != nil {
Trace("template parse file err:", err) logs.Trace("template parse file err:", err)
} else if subMods1 != nil && len(subMods1) > 0 { } else if subMods1 != nil && len(subMods1) > 0 {
t, err = _getTemplate(t, root, subMods1, others...) t, err = _getTemplate(t, root, subMods1, others...)
} }
@ -261,7 +262,7 @@ func _getTemplate(t0 *template.Template, root string, subMods [][]string, others
var subMods1 [][]string var subMods1 [][]string
t, subMods1, err = getTplDeep(root, otherFile, "", t) t, subMods1, err = getTplDeep(root, otherFile, "", t)
if err != nil { if err != nil {
Trace("template parse file err:", err) logs.Trace("template parse file err:", err)
} else if subMods1 != nil && len(subMods1) > 0 { } else if subMods1 != nil && len(subMods1) > 0 {
t, err = _getTemplate(t, root, subMods1, others...) t, err = _getTemplate(t, root, subMods1, others...)
} }