Commit e0a36fb6 authored by miraclesu's avatar miraclesu

Merge branch 'develop' into feature/orm_auto

parents 8f70df6c 85a9b054
...@@ -24,6 +24,7 @@ import ( ...@@ -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() { ...@@ -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() { ...@@ -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()))
} }
} }
...@@ -16,7 +16,6 @@ package beego ...@@ -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 ( ...@@ -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() { ...@@ -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() { ...@@ -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() { ...@@ -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() { ...@@ -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() { ...@@ -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() { ...@@ -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() { ...@@ -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
} }
......
...@@ -18,9 +18,8 @@ import ( ...@@ -18,9 +18,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/garyburd/redigo/redis"
"github.com/astaxie/beego/cache" "github.com/astaxie/beego/cache"
"github.com/garyburd/redigo/redis"
) )
func TestRedisCache(t *testing.T) { func TestRedisCache(t *testing.T) {
......
package ssdb package ssdb
import ( import (
"github.com/astaxie/beego/cache"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"github.com/astaxie/beego/cache"
) )
func TestSsdbcacheCache(t *testing.T) { func TestSsdbcacheCache(t *testing.T) {
......
...@@ -21,6 +21,7 @@ import ( ...@@ -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) { ...@@ -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
} }
......
...@@ -100,7 +100,7 @@ func TestSubDomain(t *testing.T) { ...@@ -100,7 +100,7 @@ func TestSubDomain(t *testing.T) {
/* TODO Fix this /* TODO Fix this
r, _ = http.NewRequest("GET", "http://127.0.0.1/", nil) r, _ = http.NewRequest("GET", "http://127.0.0.1/", nil)
beegoInput.Request = r beegoInput.Context.Request = r
if beegoInput.SubDomains() != "" { if beegoInput.SubDomains() != "" {
t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains()) t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains())
} }
......
...@@ -24,6 +24,7 @@ import ( ...@@ -24,6 +24,7 @@ import (
"io" "io"
"mime" "mime"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
...@@ -237,6 +238,12 @@ func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error { ...@@ -237,6 +238,12 @@ func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
// Download forces response for download file. // Download forces response for download file.
// it prepares the download response header automatically. // it prepares the download response header automatically.
func (output *BeegoOutput) Download(file string, filename ...string) { func (output *BeegoOutput) Download(file string, filename ...string) {
// check get file error, file not found or other error.
if _, err := os.Stat(file); err != nil {
http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file)
return
}
output.Header("Content-Description", "File Transfer") output.Header("Content-Description", "File Transfer")
output.Header("Content-Type", "application/octet-stream") output.Header("Content-Type", "application/octet-stream")
if len(filename) > 0 && filename[0] != "" { if len(filename) > 0 && filename[0] != "" {
......
...@@ -20,14 +20,8 @@ import ( ...@@ -20,14 +20,8 @@ import (
"testing" "testing"
"github.com/astaxie/beego/context" "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) { var FilterUser = func(ctx *context.Context) {
ctx.Output.Body([]byte("i am " + ctx.Input.Param(":last") + ctx.Input.Param(":first"))) ctx.Output.Body([]byte("i am " + ctx.Input.Param(":last") + ctx.Input.Param(":first")))
} }
......
...@@ -7,6 +7,7 @@ import ( ...@@ -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 { ...@@ -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
} }
......
...@@ -33,82 +33,77 @@ const ( ...@@ -33,82 +33,77 @@ const (
) )
// BeeLogger references the used application logger. // BeeLogger references the used application logger.
var BeeLogger = logs.NewLogger(100) var BeeLogger = logs.GetBeeLogger()
// SetLevel sets the global log level used by the simple logger. // SetLevel sets the global log level used by the simple logger.
func SetLevel(l int) { func SetLevel(l int) {
BeeLogger.SetLevel(l) logs.SetLevel(l)
} }
// SetLogFuncCall set the CallDepth, default is 3 // SetLogFuncCall set the CallDepth, default is 3
func SetLogFuncCall(b bool) { func SetLogFuncCall(b bool) {
BeeLogger.EnableFuncCallDepth(b) logs.SetLogFuncCall(b)
BeeLogger.SetLogFuncCallDepth(3)
} }
// SetLogger sets a new logger. // SetLogger sets a new logger.
func SetLogger(adaptername string, config string) error { func SetLogger(adaptername string, config string) error {
err := BeeLogger.SetLogger(adaptername, config) return logs.SetLogger(adaptername, config)
if err != nil {
return err
}
return nil
} }
// Emergency logs a message at emergency level. // Emergency logs a message at emergency level.
func Emergency(v ...interface{}) { func Emergency(v ...interface{}) {
BeeLogger.Emergency(generateFmtStr(len(v)), v...) logs.Emergency(generateFmtStr(len(v)), v...)
} }
// Alert logs a message at alert level. // Alert logs a message at alert level.
func Alert(v ...interface{}) { func Alert(v ...interface{}) {
BeeLogger.Alert(generateFmtStr(len(v)), v...) logs.Alert(generateFmtStr(len(v)), v...)
} }
// Critical logs a message at critical level. // Critical logs a message at critical level.
func Critical(v ...interface{}) { func Critical(v ...interface{}) {
BeeLogger.Critical(generateFmtStr(len(v)), v...) logs.Critical(generateFmtStr(len(v)), v...)
} }
// Error logs a message at error level. // Error logs a message at error level.
func Error(v ...interface{}) { func Error(v ...interface{}) {
BeeLogger.Error(generateFmtStr(len(v)), v...) logs.Error(generateFmtStr(len(v)), v...)
} }
// Warning logs a message at warning level. // Warning logs a message at warning level.
func Warning(v ...interface{}) { func Warning(v ...interface{}) {
BeeLogger.Warning(generateFmtStr(len(v)), v...) logs.Warning(generateFmtStr(len(v)), v...)
} }
// Warn compatibility alias for Warning() // Warn compatibility alias for Warning()
func Warn(v ...interface{}) { func Warn(v ...interface{}) {
BeeLogger.Warn(generateFmtStr(len(v)), v...) logs.Warn(generateFmtStr(len(v)), v...)
} }
// Notice logs a message at notice level. // Notice logs a message at notice level.
func Notice(v ...interface{}) { func Notice(v ...interface{}) {
BeeLogger.Notice(generateFmtStr(len(v)), v...) logs.Notice(generateFmtStr(len(v)), v...)
} }
// Informational logs a message at info level. // Informational logs a message at info level.
func Informational(v ...interface{}) { func Informational(v ...interface{}) {
BeeLogger.Informational(generateFmtStr(len(v)), v...) logs.Informational(generateFmtStr(len(v)), v...)
} }
// Info compatibility alias for Warning() // Info compatibility alias for Warning()
func Info(v ...interface{}) { func Info(v ...interface{}) {
BeeLogger.Info(generateFmtStr(len(v)), v...) logs.Info(generateFmtStr(len(v)), v...)
} }
// Debug logs a message at debug level. // Debug logs a message at debug level.
func Debug(v ...interface{}) { func Debug(v ...interface{}) {
BeeLogger.Debug(generateFmtStr(len(v)), v...) logs.Debug(generateFmtStr(len(v)), v...)
} }
// Trace logs a message at trace level. // Trace logs a message at trace level.
// compatibility alias for Warning() // compatibility alias for Warning()
func Trace(v ...interface{}) { func Trace(v ...interface{}) {
BeeLogger.Trace(generateFmtStr(len(v)), v...) logs.Trace(generateFmtStr(len(v)), v...)
} }
func generateFmtStr(n int) string { func generateFmtStr(n int) string {
......
...@@ -113,5 +113,5 @@ func (c *connWriter) needToConnectOnMsg() bool { ...@@ -113,5 +113,5 @@ func (c *connWriter) needToConnectOnMsg() bool {
} }
func init() { func init() {
Register("conn", NewConn) Register(AdapterConn, NewConn)
} }
...@@ -97,5 +97,5 @@ func (c *consoleWriter) Flush() { ...@@ -97,5 +97,5 @@ func (c *consoleWriter) Flush() {
} }
func init() { func init() {
Register("console", NewConsole) Register(AdapterConsole, NewConsole)
} }
...@@ -76,5 +76,5 @@ func (el *esLogger) Flush() { ...@@ -76,5 +76,5 @@ func (el *esLogger) Flush() {
} }
func init() { func init() {
logs.Register("es", NewES) logs.Register(logs.AdapterEs, NewES)
} }
...@@ -282,5 +282,5 @@ func (w *fileLogWriter) Flush() { ...@@ -282,5 +282,5 @@ func (w *fileLogWriter) Flush() {
} }
func init() { func init() {
Register("file", newFileWriter) Register(AdapterFile, newFileWriter)
} }
...@@ -35,10 +35,12 @@ package logs ...@@ -35,10 +35,12 @@ package logs
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"path" "path"
"runtime" "runtime"
"strconv" "strconv"
"strings"
"sync" "sync"
"time" "time"
) )
...@@ -55,16 +57,28 @@ const ( ...@@ -55,16 +57,28 @@ const (
LevelDebug LevelDebug
) )
// Legacy loglevel constants to ensure backwards compatibility. // levelLogLogger is defined to implement log.Logger
// // the real log level will be LevelEmergency
// Deprecated: will be removed in 1.5.0. const levelLoggerImpl = -1
// Name for adapter with beego official support
const (
AdapterConsole = "console"
AdapterFile = "file"
AdapterMultiFile = "multifile"
AdapterMail = "stmp"
AdapterConn = "conn"
AdapterEs = "es"
)
// Legacy log level constants to ensure backwards compatibility.
const ( const (
LevelInfo = LevelInformational LevelInfo = LevelInformational
LevelTrace = LevelDebug LevelTrace = LevelDebug
LevelWarn = LevelWarning LevelWarn = LevelWarning
) )
type loggerType func() Logger type newLoggerFunc func() Logger
// Logger defines the behavior of a log provider. // Logger defines the behavior of a log provider.
type Logger interface { type Logger interface {
...@@ -74,12 +88,13 @@ type Logger interface { ...@@ -74,12 +88,13 @@ type Logger interface {
Flush() 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. // Register makes a log provide available by the provided name.
// If Register is called twice with the same name or if driver is nil, // If Register is called twice with the same name or if driver is nil,
// it panics. // it panics.
func Register(name string, log loggerType) { func Register(name string, log newLoggerFunc) {
if log == nil { if log == nil {
panic("logs: Register provide is nil") panic("logs: Register provide is nil")
} }
...@@ -94,15 +109,19 @@ func Register(name string, log loggerType) { ...@@ -94,15 +109,19 @@ func Register(name string, log loggerType) {
type BeeLogger struct { type BeeLogger struct {
lock sync.Mutex lock sync.Mutex
level int level int
init bool
enableFuncCallDepth bool enableFuncCallDepth bool
loggerFuncCallDepth int loggerFuncCallDepth int
asynchronous bool asynchronous bool
msgChanLen int64
msgChan chan *logMsg msgChan chan *logMsg
signalChan chan string signalChan chan string
wg sync.WaitGroup wg sync.WaitGroup
outputs []*nameLogger outputs []*nameLogger
} }
const defaultAsyncMsgLen = 1e3
type nameLogger struct { type nameLogger struct {
Logger Logger
name string name string
...@@ -119,18 +138,28 @@ var logMsgPool *sync.Pool ...@@ -119,18 +138,28 @@ var logMsgPool *sync.Pool
// NewLogger returns a new BeeLogger. // NewLogger returns a new BeeLogger.
// channelLen means the number of messages in chan(used where asynchronous is true). // 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. // 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 := new(BeeLogger)
bl.level = LevelDebug bl.level = LevelDebug
bl.loggerFuncCallDepth = 2 bl.loggerFuncCallDepth = 2
bl.msgChan = make(chan *logMsg, channelLen) bl.msgChanLen = append(channelLens, 0)[0]
if bl.msgChanLen <= 0 {
bl.msgChanLen = defaultAsyncMsgLen
}
bl.signalChan = make(chan string, 1) bl.signalChan = make(chan string, 1)
bl.setLogger(AdapterConsole)
return bl return bl
} }
// Async set the log to asynchronous and start the goroutine // Async set the log to asynchronous and start the goroutine
func (bl *BeeLogger) Async() *BeeLogger { func (bl *BeeLogger) Async() *BeeLogger {
bl.lock.Lock()
defer bl.lock.Unlock()
if bl.asynchronous {
return bl
}
bl.asynchronous = true bl.asynchronous = true
bl.msgChan = make(chan *logMsg, bl.msgChanLen)
logMsgPool = &sync.Pool{ logMsgPool = &sync.Pool{
New: func() interface{} { New: func() interface{} {
return &logMsg{} return &logMsg{}
...@@ -143,10 +172,8 @@ func (bl *BeeLogger) Async() *BeeLogger { ...@@ -143,10 +172,8 @@ func (bl *BeeLogger) Async() *BeeLogger {
// SetLogger provides a given logger adapter into BeeLogger with config string. // SetLogger provides a given logger adapter into BeeLogger with config string.
// config need to be correct JSON as string: {"interval":360}. // 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 {
bl.lock.Lock() config := append(configs, "{}")[0]
defer bl.lock.Unlock()
for _, l := range bl.outputs { for _, l := range bl.outputs {
if l.name == adapterName { if l.name == adapterName {
return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName) return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName)
...@@ -168,6 +195,18 @@ func (bl *BeeLogger) SetLogger(adapterName string, config string) error { ...@@ -168,6 +195,18 @@ func (bl *BeeLogger) SetLogger(adapterName string, config string) error {
return nil 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. // DelLogger remove a logger adapter in BeeLogger.
func (bl *BeeLogger) DelLogger(adapterName string) error { func (bl *BeeLogger) DelLogger(adapterName string) error {
bl.lock.Lock() bl.lock.Lock()
...@@ -204,15 +243,29 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) { ...@@ -204,15 +243,29 @@ func (bl *BeeLogger) Write(p []byte) (n int, err error) {
if p[len(p)-1] == '\n' { if p[len(p)-1] == '\n' {
p = p[0 : len(p)-1] p = p[0 : len(p)-1]
} }
// set LevelCritical to ensure all log message will be write out // set levelLoggerImpl to ensure all log message will be write out
err = bl.writeMsg(LevelCritical, string(p)) err = bl.writeMsg(levelLoggerImpl, string(p))
if err == nil { if err == nil {
return len(p), err return len(p), err
} }
return 0, 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 !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
} else {
msg = levelPrefix[logLevel] + msg
}
if len(v) > 0 {
msg = fmt.Sprintf(msg, v...)
}
when := time.Now() when := time.Now()
if bl.enableFuncCallDepth { if bl.enableFuncCallDepth {
_, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth)
...@@ -289,8 +342,7 @@ func (bl *BeeLogger) Emergency(format string, v ...interface{}) { ...@@ -289,8 +342,7 @@ func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
if LevelEmergency > bl.level { if LevelEmergency > bl.level {
return return
} }
msg := fmt.Sprintf("[M] "+format, v...) bl.writeMsg(LevelEmergency, format, v...)
bl.writeMsg(LevelEmergency, msg)
} }
// Alert Log ALERT level message. // Alert Log ALERT level message.
...@@ -298,8 +350,7 @@ func (bl *BeeLogger) Alert(format string, v ...interface{}) { ...@@ -298,8 +350,7 @@ func (bl *BeeLogger) Alert(format string, v ...interface{}) {
if LevelAlert > bl.level { if LevelAlert > bl.level {
return return
} }
msg := fmt.Sprintf("[A] "+format, v...) bl.writeMsg(LevelAlert, format, v...)
bl.writeMsg(LevelAlert, msg)
} }
// Critical Log CRITICAL level message. // Critical Log CRITICAL level message.
...@@ -307,8 +358,7 @@ func (bl *BeeLogger) Critical(format string, v ...interface{}) { ...@@ -307,8 +358,7 @@ func (bl *BeeLogger) Critical(format string, v ...interface{}) {
if LevelCritical > bl.level { if LevelCritical > bl.level {
return return
} }
msg := fmt.Sprintf("[C] "+format, v...) bl.writeMsg(LevelCritical, format, v...)
bl.writeMsg(LevelCritical, msg)
} }
// Error Log ERROR level message. // Error Log ERROR level message.
...@@ -316,17 +366,12 @@ func (bl *BeeLogger) Error(format string, v ...interface{}) { ...@@ -316,17 +366,12 @@ func (bl *BeeLogger) Error(format string, v ...interface{}) {
if LevelError > bl.level { if LevelError > bl.level {
return return
} }
msg := fmt.Sprintf("[E] "+format, v...) bl.writeMsg(LevelError, format, v...)
bl.writeMsg(LevelError, msg)
} }
// Warning Log WARNING level message. // Warning Log WARNING level message.
func (bl *BeeLogger) Warning(format string, v ...interface{}) { func (bl *BeeLogger) Warning(format string, v ...interface{}) {
if LevelWarning > bl.level { bl.Warn(format, v...)
return
}
msg := fmt.Sprintf("[W] "+format, v...)
bl.writeMsg(LevelWarning, msg)
} }
// Notice Log NOTICE level message. // Notice Log NOTICE level message.
...@@ -334,17 +379,12 @@ func (bl *BeeLogger) Notice(format string, v ...interface{}) { ...@@ -334,17 +379,12 @@ func (bl *BeeLogger) Notice(format string, v ...interface{}) {
if LevelNotice > bl.level { if LevelNotice > bl.level {
return return
} }
msg := fmt.Sprintf("[N] "+format, v...) bl.writeMsg(LevelNotice, format, v...)
bl.writeMsg(LevelNotice, msg)
} }
// Informational Log INFORMATIONAL level message. // Informational Log INFORMATIONAL level message.
func (bl *BeeLogger) Informational(format string, v ...interface{}) { func (bl *BeeLogger) Informational(format string, v ...interface{}) {
if LevelInformational > bl.level { bl.Info(format, v...)
return
}
msg := fmt.Sprintf("[I] "+format, v...)
bl.writeMsg(LevelInformational, msg)
} }
// Debug Log DEBUG level message. // Debug Log DEBUG level message.
...@@ -352,38 +392,31 @@ func (bl *BeeLogger) Debug(format string, v ...interface{}) { ...@@ -352,38 +392,31 @@ func (bl *BeeLogger) Debug(format string, v ...interface{}) {
if LevelDebug > bl.level { if LevelDebug > bl.level {
return return
} }
msg := fmt.Sprintf("[D] "+format, v...) bl.writeMsg(LevelDebug, format, v...)
bl.writeMsg(LevelDebug, msg)
} }
// Warn Log WARN level message. // Warn Log WARN level message.
// compatibility alias for Warning() // compatibility alias for Warning()
func (bl *BeeLogger) Warn(format string, v ...interface{}) { func (bl *BeeLogger) Warn(format string, v ...interface{}) {
if LevelWarning > bl.level { if LevelWarn > bl.level {
return return
} }
msg := fmt.Sprintf("[W] "+format, v...) bl.writeMsg(LevelWarn, format, v...)
bl.writeMsg(LevelWarning, msg)
} }
// Info Log INFO level message. // Info Log INFO level message.
// compatibility alias for Informational() // compatibility alias for Informational()
func (bl *BeeLogger) Info(format string, v ...interface{}) { func (bl *BeeLogger) Info(format string, v ...interface{}) {
if LevelInformational > bl.level { if LevelInfo > bl.level {
return return
} }
msg := fmt.Sprintf("[I] "+format, v...) bl.writeMsg(LevelInfo, format, v...)
bl.writeMsg(LevelInformational, msg)
} }
// Trace Log TRACE level message. // Trace Log TRACE level message.
// compatibility alias for Debug() // compatibility alias for Debug()
func (bl *BeeLogger) Trace(format string, v ...interface{}) { func (bl *BeeLogger) Trace(format string, v ...interface{}) {
if LevelDebug > bl.level { bl.Debug(format, v...)
return
}
msg := fmt.Sprintf("[D] "+format, v...)
bl.writeMsg(LevelDebug, msg)
} }
// Flush flush all chan data. // Flush flush all chan data.
...@@ -402,6 +435,7 @@ func (bl *BeeLogger) Close() { ...@@ -402,6 +435,7 @@ func (bl *BeeLogger) Close() {
if bl.asynchronous { if bl.asynchronous {
bl.signalChan <- "close" bl.signalChan <- "close"
bl.wg.Wait() bl.wg.Wait()
close(bl.msgChan)
} else { } else {
bl.flush() bl.flush()
for _, l := range bl.outputs { for _, l := range bl.outputs {
...@@ -409,7 +443,6 @@ func (bl *BeeLogger) Close() { ...@@ -409,7 +443,6 @@ func (bl *BeeLogger) Close() {
} }
bl.outputs = nil bl.outputs = nil
} }
close(bl.msgChan)
close(bl.signalChan) close(bl.signalChan)
} }
...@@ -423,16 +456,165 @@ func (bl *BeeLogger) Reset() { ...@@ -423,16 +456,165 @@ func (bl *BeeLogger) Reset() {
} }
func (bl *BeeLogger) flush() { func (bl *BeeLogger) flush() {
for { if bl.asynchronous {
if len(bl.msgChan) > 0 { for {
bm := <-bl.msgChan if len(bl.msgChan) > 0 {
bl.writeToLoggers(bm.when, bm.msg, bm.level) bm := <-bl.msgChan
logMsgPool.Put(bm) bl.writeToLoggers(bm.when, bm.msg, bm.level)
continue logMsgPool.Put(bm)
continue
}
break
} }
break
} }
for _, l := range bl.outputs { for _, l := range bl.outputs {
l.Flush() l.Flush()
} }
} }
// beeLogger references the used application logger.
var beeLogger *BeeLogger = NewLogger()
// 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] `, strings.ToUpper(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()
}
func Async() *BeeLogger {
return beeLogger.Async()
}
// 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(adapter string, config ...string) error {
err := beeLogger.SetLogger(adapter, config...)
if err != nil {
return err
}
return nil
}
// Emergency logs a message at emergency level.
func Emergency(f interface{}, v ...interface{}) {
beeLogger.Emergency(formatLog(f, v...))
}
// Alert logs a message at alert level.
func Alert(f interface{}, v ...interface{}) {
beeLogger.Alert(formatLog(f, v...))
}
// Critical logs a message at critical level.
func Critical(f interface{}, v ...interface{}) {
beeLogger.Critical(formatLog(f, v...))
}
// Error logs a message at error level.
func Error(f interface{}, v ...interface{}) {
beeLogger.Error(formatLog(f, v...))
}
// Warning logs a message at warning level.
func Warning(f interface{}, v ...interface{}) {
beeLogger.Warn(formatLog(f, v...))
}
// Warn compatibility alias for Warning()
func Warn(f interface{}, v ...interface{}) {
beeLogger.Warn(formatLog(f, v...))
}
// Notice logs a message at notice level.
func Notice(f interface{}, v ...interface{}) {
beeLogger.Notice(formatLog(f, v...))
}
// Informational logs a message at info level.
func Informational(f interface{}, v ...interface{}) {
beeLogger.Info(formatLog(f, v...))
}
// Info compatibility alias for Warning()
func Info(f interface{}, v ...interface{}) {
beeLogger.Info(formatLog(f, v...))
}
// Debug logs a message at debug level.
func Debug(f interface{}, v ...interface{}) {
beeLogger.Debug(formatLog(f, v...))
}
// Trace logs a message at trace level.
// compatibility alias for Warning()
func Trace(f interface{}, v ...interface{}) {
beeLogger.Trace(formatLog(f, v...))
}
func formatLog(f interface{}, v ...interface{}) string {
var msg 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 {
//do not contain format char
msg += strings.Repeat(" %v", len(v))
}
default:
msg = fmt.Sprint(f)
if len(v) == 0 {
return msg
}
msg += strings.Repeat(" %v", len(v))
}
return fmt.Sprintf(msg, v...)
}
...@@ -112,5 +112,5 @@ func newFilesWriter() Logger { ...@@ -112,5 +112,5 @@ func newFilesWriter() Logger {
} }
func init() { func init() {
Register("multifile", newFilesWriter) Register(AdapterMultiFile, newFilesWriter)
} }
...@@ -156,5 +156,5 @@ func (s *SMTPWriter) Destroy() { ...@@ -156,5 +156,5 @@ func (s *SMTPWriter) Destroy() {
} }
func init() { func init() {
Register("smtp", newSMTPWriter) Register(AdapterMail, newSMTPWriter)
} }
...@@ -33,7 +33,7 @@ import ( ...@@ -33,7 +33,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
) )
...@@ -90,7 +90,7 @@ func (m *Migration) Reset() { ...@@ -90,7 +90,7 @@ func (m *Migration) Reset() {
func (m *Migration) Exec(name, status string) error { func (m *Migration) Exec(name, status string) error {
o := orm.NewOrm() o := orm.NewOrm()
for _, s := range m.sqls { for _, s := range m.sqls {
beego.Info("exec sql:", s) logs.Info("exec sql:", s)
r := o.Raw(s) r := o.Raw(s)
_, err := r.Exec() _, err := r.Exec()
if err != nil { if err != nil {
...@@ -144,20 +144,20 @@ func Upgrade(lasttime int64) error { ...@@ -144,20 +144,20 @@ func Upgrade(lasttime int64) error {
i := 0 i := 0
for _, v := range sm { for _, v := range sm {
if v.created > lasttime { if v.created > lasttime {
beego.Info("start upgrade", v.name) logs.Info("start upgrade", v.name)
v.m.Reset() v.m.Reset()
v.m.Up() v.m.Up()
err := v.m.Exec(v.name, "up") err := v.m.Exec(v.name, "up")
if err != nil { if err != nil {
beego.Error("execute error:", err) logs.Error("execute error:", err)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return err return err
} }
beego.Info("end upgrade:", v.name) logs.Info("end upgrade:", v.name)
i++ i++
} }
} }
beego.Info("total success upgrade:", i, " migration") logs.Info("total success upgrade:", i, " migration")
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return nil return nil
} }
...@@ -165,20 +165,20 @@ func Upgrade(lasttime int64) error { ...@@ -165,20 +165,20 @@ func Upgrade(lasttime int64) error {
// Rollback rollback the migration by the name // Rollback rollback the migration by the name
func Rollback(name string) error { func Rollback(name string) error {
if v, ok := migrationMap[name]; ok { if v, ok := migrationMap[name]; ok {
beego.Info("start rollback") logs.Info("start rollback")
v.Reset() v.Reset()
v.Down() v.Down()
err := v.Exec(name, "down") err := v.Exec(name, "down")
if err != nil { if err != nil {
beego.Error("execute error:", err) logs.Error("execute error:", err)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return err return err
} }
beego.Info("end rollback") logs.Info("end rollback")
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return nil return nil
} }
beego.Error("not exist the migrationMap name:" + name) logs.Error("not exist the migrationMap name:" + name)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return errors.New("not exist the migrationMap name:" + name) return errors.New("not exist the migrationMap name:" + name)
} }
...@@ -191,23 +191,23 @@ func Reset() error { ...@@ -191,23 +191,23 @@ func Reset() error {
for j := len(sm) - 1; j >= 0; j-- { for j := len(sm) - 1; j >= 0; j-- {
v := sm[j] v := sm[j]
if isRollBack(v.name) { if isRollBack(v.name) {
beego.Info("skip the", v.name) logs.Info("skip the", v.name)
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
continue continue
} }
beego.Info("start reset:", v.name) logs.Info("start reset:", v.name)
v.m.Reset() v.m.Reset()
v.m.Down() v.m.Down()
err := v.m.Exec(v.name, "down") err := v.m.Exec(v.name, "down")
if err != nil { if err != nil {
beego.Error("execute error:", err) logs.Error("execute error:", err)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return err return err
} }
i++ 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) time.Sleep(2 * time.Second)
return nil return nil
} }
...@@ -216,7 +216,7 @@ func Reset() error { ...@@ -216,7 +216,7 @@ func Reset() error {
func Refresh() error { func Refresh() error {
err := Reset() err := Reset()
if err != nil { if err != nil {
beego.Error("execute error:", err) logs.Error("execute error:", err)
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
return err return err
} }
...@@ -265,7 +265,7 @@ func isRollBack(name string) bool { ...@@ -265,7 +265,7 @@ func isRollBack(name string) bool {
var maps []orm.Params var maps []orm.Params
num, err := o.Raw("select * from migrations where `name` = ? order by id_migration desc", name).Values(&maps) num, err := o.Raw("select * from migrations where `name` = ? order by id_migration desc", name).Values(&maps)
if err != nil { if err != nil {
beego.Info("get name has error", err) logs.Info("get name has error", err)
return false return false
} }
if num <= 0 { if num <= 0 {
......
...@@ -123,14 +123,16 @@ func (d *dbBasePostgres) ReplaceMarks(query *string) { ...@@ -123,14 +123,16 @@ func (d *dbBasePostgres) ReplaceMarks(query *string) {
} }
// make returning sql support for postgresql. // make returning sql support for postgresql.
func (d *dbBasePostgres) HasReturningID(mi *modelInfo, query *string) (has bool) { func (d *dbBasePostgres) HasReturningID(mi *modelInfo, query *string) bool {
if mi.fields.pk.auto { fi := mi.fields.pk
if query != nil { if fi.fieldType&IsPositiveIntegerField == 0 && fi.fieldType&IsIntegerField == 0 {
*query = fmt.Sprintf(`%s RETURNING "%s"`, *query, mi.fields.pk.column) return false
} }
has = true
if query != nil {
*query = fmt.Sprintf(`%s RETURNING "%s"`, *query, fi.column)
} }
return return true
} }
// show table sql for postgresql. // show table sql for postgresql.
......
...@@ -392,6 +392,11 @@ type IntegerPk struct { ...@@ -392,6 +392,11 @@ type IntegerPk struct {
Value string Value string
} }
type UintPk struct {
Id uint32 `orm:"pk"`
Name string
}
var DBARGS = struct { var DBARGS = struct {
Driver string Driver string
Source string Source string
......
...@@ -140,7 +140,14 @@ func (o *orm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, i ...@@ -140,7 +140,14 @@ func (o *orm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, i
return (err == nil), id, err return (err == nil), id, err
} }
return false, ind.FieldByIndex(mi.fields.pk.fieldIndex).Int(), err id, vid := int64(0), ind.FieldByIndex(mi.fields.pk.fieldIndex)
if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
id = int64(vid.Uint())
} else {
id = vid.Int()
}
return false, id, err
} }
// insert model data to database // insert model data to database
......
...@@ -191,6 +191,7 @@ func TestSyncDb(t *testing.T) { ...@@ -191,6 +191,7 @@ func TestSyncDb(t *testing.T) {
RegisterModel(new(InLine)) RegisterModel(new(InLine))
RegisterModel(new(InLineOneToOne)) RegisterModel(new(InLineOneToOne))
RegisterModel(new(IntegerPk)) RegisterModel(new(IntegerPk))
RegisterModel(new(UintPk))
err := RunSyncdb("default", true, Debug) err := RunSyncdb("default", true, Debug)
throwFail(t, err) throwFail(t, err)
...@@ -213,6 +214,7 @@ func TestRegisterModels(t *testing.T) { ...@@ -213,6 +214,7 @@ func TestRegisterModels(t *testing.T) {
RegisterModel(new(InLine)) RegisterModel(new(InLine))
RegisterModel(new(InLineOneToOne)) RegisterModel(new(InLineOneToOne))
RegisterModel(new(IntegerPk)) RegisterModel(new(IntegerPk))
RegisterModel(new(UintPk))
BootStrap() BootStrap()
...@@ -2034,3 +2036,26 @@ func TestInsertAuto(t *testing.T) { ...@@ -2034,3 +2036,26 @@ func TestInsertAuto(t *testing.T) {
throwFail(t, err) throwFail(t, err)
throwFail(t, AssertIs(id, sid)) throwFail(t, AssertIs(id, sid))
} }
func TestUintPk(t *testing.T) {
name := "go"
u := &UintPk{
Id: 8,
Name: name,
}
created, pk, err := dORM.ReadOrCreate(u, "Id")
throwFail(t, err)
throwFail(t, AssertIs(created, true))
throwFail(t, AssertIs(u.Name, name))
nu := &UintPk{Id: 8}
created, pk, err = dORM.ReadOrCreate(nu, "Id")
throwFail(t, err)
throwFail(t, AssertIs(created, false))
throwFail(t, AssertIs(nu.Id, u.Id))
throwFail(t, AssertIs(pk, u.Id))
throwFail(t, AssertIs(nu.Name, name))
dORM.Delete(u)
}
...@@ -27,6 +27,7 @@ import ( ...@@ -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 { ...@@ -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 ...@@ -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
......
...@@ -28,6 +28,7 @@ import ( ...@@ -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 ...@@ -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) ...@@ -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) ...@@ -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: ...@@ -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) { ...@@ -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 {
......
...@@ -21,6 +21,7 @@ import ( ...@@ -21,6 +21,7 @@ import (
"testing" "testing"
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
) )
type TestController struct { type TestController struct {
...@@ -94,7 +95,7 @@ func TestUrlFor(t *testing.T) { ...@@ -94,7 +95,7 @@ func TestUrlFor(t *testing.T) {
handler.Add("/api/list", &TestController{}, "*:List") handler.Add("/api/list", &TestController{}, "*:List")
handler.Add("/person/:last/:first", &TestController{}, "*:Param") handler.Add("/person/:last/:first", &TestController{}, "*:Param")
if a := handler.URLFor("TestController.List"); a != "/api/list" { if a := handler.URLFor("TestController.List"); a != "/api/list" {
Info(a) logs.Info(a)
t.Errorf("TestController.List must equal to /api/list") t.Errorf("TestController.List must equal to /api/list")
} }
if a := handler.URLFor("TestController.Param", ":last", "xie", ":first", "asta"); a != "/person/xie/asta" { if a := handler.URLFor("TestController.Param", ":last", "xie", ":first", "asta"); a != "/person/xie/asta" {
...@@ -120,24 +121,24 @@ func TestUrlFor2(t *testing.T) { ...@@ -120,24 +121,24 @@ func TestUrlFor2(t *testing.T) {
handler.Add("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", &TestController{}, "*:Param") handler.Add("/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html", &TestController{}, "*:Param")
handler.Add("/:year:int/:month:int/:title/:entid", &TestController{}) handler.Add("/:year:int/:month:int/:title/:entid", &TestController{})
if handler.URLFor("TestController.GetURL", ":username", "astaxie") != "/v1/astaxie/edit" { 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") t.Errorf("TestController.List must equal to /v1/astaxie/edit")
} }
if handler.URLFor("TestController.List", ":v", "za", ":id", "12", ":page", "123") != if handler.URLFor("TestController.List", ":v", "za", ":id", "12", ":page", "123") !=
"/v1/za/cms_12_123.html" { "/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") t.Errorf("TestController.List must equal to /v1/za/cms_12_123.html")
} }
if handler.URLFor("TestController.Param", ":v", "za", ":id", "12", ":page", "123") != if handler.URLFor("TestController.Param", ":v", "za", ":id", "12", ":page", "123") !=
"/v1/za_cms/ttt_12_123.html" { "/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") t.Errorf("TestController.List must equal to /v1/za_cms/ttt_12_123.html")
} }
if handler.URLFor("TestController.Get", ":year", "1111", ":month", "11", if handler.URLFor("TestController.Get", ":year", "1111", ":month", "11",
":title", "aaaa", ":entid", "aaaa") != ":title", "aaaa", ":entid", "aaaa") !=
"/1111/11/aaaa/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") t.Errorf("TestController.Get must equal to /1111/11/aaaa/aaaa")
} }
} }
......
...@@ -115,7 +115,6 @@ func (st *SessionStore) SessionRelease(w http.ResponseWriter) { ...@@ -115,7 +115,6 @@ func (st *SessionStore) SessionRelease(w http.ResponseWriter) {
} }
st.c.Exec("UPDATE "+TableName+" set `session_data`=?, `session_expiry`=? where session_key=?", st.c.Exec("UPDATE "+TableName+" set `session_data`=?, `session_expiry`=? where session_key=?",
b, time.Now().Unix(), st.sid) b, time.Now().Unix(), st.sid)
} }
// Provider mysql session provider // Provider mysql session provider
......
...@@ -16,7 +16,6 @@ package session ...@@ -16,7 +16,6 @@ package session
import ( import (
"errors" "errors"
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
...@@ -82,14 +81,17 @@ func (fs *FileSessionStore) SessionID() string { ...@@ -82,14 +81,17 @@ func (fs *FileSessionStore) SessionID() string {
func (fs *FileSessionStore) SessionRelease(w http.ResponseWriter) { func (fs *FileSessionStore) SessionRelease(w http.ResponseWriter) {
b, err := EncodeGob(fs.values) b, err := EncodeGob(fs.values)
if err != nil { if err != nil {
SLogger.Println(err)
return return
} }
_, err = os.Stat(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid)) _, err = os.Stat(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid))
var f *os.File var f *os.File
if err == nil { if err == nil {
f, err = os.OpenFile(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid), os.O_RDWR, 0777) f, err = os.OpenFile(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid), os.O_RDWR, 0777)
SLogger.Println(err)
} else if os.IsNotExist(err) { } else if os.IsNotExist(err) {
f, err = os.Create(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid)) f, err = os.Create(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid))
SLogger.Println(err)
} else { } else {
return return
} }
...@@ -123,7 +125,7 @@ func (fp *FileProvider) SessionRead(sid string) (Store, error) { ...@@ -123,7 +125,7 @@ func (fp *FileProvider) SessionRead(sid string) (Store, error) {
err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777) err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
if err != nil { if err != nil {
println(err.Error()) SLogger.Println(err.Error())
} }
_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) _, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
var f *os.File var f *os.File
...@@ -191,7 +193,7 @@ func (fp *FileProvider) SessionAll() int { ...@@ -191,7 +193,7 @@ func (fp *FileProvider) SessionAll() int {
return a.visit(path, f, err) return a.visit(path, f, err)
}) })
if err != nil { if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err) SLogger.Printf("filepath.Walk() returned %v\n", err)
return 0 return 0
} }
return a.total return a.total
...@@ -205,11 +207,11 @@ func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error) { ...@@ -205,11 +207,11 @@ func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error) {
err := os.MkdirAll(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])), 0777) err := os.MkdirAll(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])), 0777)
if err != nil { if err != nil {
println(err.Error()) SLogger.Println(err.Error())
} }
err = os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777) err = os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
if err != nil { if err != nil {
println(err.Error()) SLogger.Println(err.Error())
} }
_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) _, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
var newf *os.File var newf *os.File
......
...@@ -32,8 +32,11 @@ import ( ...@@ -32,8 +32,11 @@ import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"log"
"net/http" "net/http"
"net/url" "net/url"
"os"
"time" "time"
) )
...@@ -61,6 +64,9 @@ type Provider interface { ...@@ -61,6 +64,9 @@ type Provider interface {
var provides = make(map[string]Provider) var provides = make(map[string]Provider)
// SLogger a helpful variable to log information about session
var SLogger = NewSessionLog(os.Stderr)
// Register makes a session provide available by the provided name. // Register makes a session provide available by the provided name.
// If Register is called twice with the same name or if driver is nil, // If Register is called twice with the same name or if driver is nil,
// it panics. // it panics.
...@@ -296,3 +302,15 @@ func (manager *Manager) isSecure(req *http.Request) bool { ...@@ -296,3 +302,15 @@ func (manager *Manager) isSecure(req *http.Request) bool {
} }
return true return true
} }
// Log implement the log.Logger
type Log struct {
*log.Logger
}
// NewSessionLog set io.Writer to create a Logger for session.
func NewSessionLog(out io.Writer) *Log {
sl := new(Log)
sl.Logger = log.New(out, "[SESSION]", 1e9)
return sl
}
...@@ -27,6 +27,7 @@ import ( ...@@ -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) { ...@@ -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) { ...@@ -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
......
...@@ -26,6 +26,7 @@ import ( ...@@ -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 { ...@@ -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 { ...@@ -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 ...@@ -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 ...@@ -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...)
} }
......
...@@ -69,6 +69,7 @@ import ( ...@@ -69,6 +69,7 @@ import (
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/cache" "github.com/astaxie/beego/cache"
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
...@@ -139,7 +140,7 @@ func (c *Captcha) Handler(ctx *context.Context) { ...@@ -139,7 +140,7 @@ func (c *Captcha) Handler(ctx *context.Context) {
if err := c.store.Put(key, chars, c.Expiration); err != nil { if err := c.store.Put(key, chars, c.Expiration); err != nil {
ctx.Output.SetStatus(500) ctx.Output.SetStatus(500)
ctx.WriteString("captcha reload error") ctx.WriteString("captcha reload error")
beego.Error("Reload Create Captcha Error:", err) logs.Error("Reload Create Captcha Error:", err)
return return
} }
} else { } else {
...@@ -154,7 +155,7 @@ func (c *Captcha) Handler(ctx *context.Context) { ...@@ -154,7 +155,7 @@ func (c *Captcha) Handler(ctx *context.Context) {
img := NewImage(chars, c.StdWidth, c.StdHeight) img := NewImage(chars, c.StdWidth, c.StdHeight)
if _, err := img.WriteTo(ctx.ResponseWriter); err != nil { 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) { ...@@ -162,7 +163,7 @@ func (c *Captcha) Handler(ctx *context.Context) {
func (c *Captcha) CreateCaptchaHTML() template.HTML { func (c *Captcha) CreateCaptchaHTML() template.HTML {
value, err := c.CreateCaptcha() value, err := c.CreateCaptcha()
if err != nil { if err != nil {
beego.Error("Create Captcha Error:", err) logs.Error("Create Captcha Error:", err)
return "" return ""
} }
......
...@@ -18,7 +18,7 @@ import ( ...@@ -18,7 +18,7 @@ import (
"github.com/astaxie/beego/context" "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) { func SetPaginator(context *context.Context, per int, nums int64) (paginator *Paginator) {
paginator = NewPaginator(context.Request, per, nums) paginator = NewPaginator(context.Request, per, nums)
context.Input.SetData("paginator", &paginator) context.Input.SetData("paginator", &paginator)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment