gorm/logger.go

71 lines
1.6 KiB
Go
Raw Normal View History

2013-11-11 05:05:14 +04:00
package gorm
2013-11-11 07:11:49 +04:00
import (
"fmt"
"log"
"os"
2013-11-11 07:53:56 +04:00
"regexp"
2013-11-11 11:48:31 +04:00
"time"
2013-11-11 07:11:49 +04:00
)
2013-11-11 05:05:14 +04:00
type Logger interface {
Print(v ...interface{})
}
2013-11-11 13:16:15 +04:00
type defaultLogger struct {
*log.Logger
}
func (logger defaultLogger) Print(v ...interface{}) {
if len(v) > 1 {
level := v[0]
tim := "\033[33m[" + time.Now().Format("2006-01-02 15:04:05") + "]\033[0m"
if level == "sql" {
dur := v[1]
sql := fmt.Sprintf(regexp.MustCompile(`(\$\d+)|\?`).ReplaceAllString(v[2].(string), "'%v'"), v[3].([]interface{})...)
dur = fmt.Sprintf(" \033[36;1m[%.2fms]\033[0m ", float64(dur.(time.Duration).Nanoseconds()/1e4)/100.0)
logger.Println(tim, dur, sql)
} else {
messages := []interface{}{"\033[31m"}
messages = append(messages, v...)
messages = append(messages, "\033[0m")
logger.Println(messages...)
}
}
}
var default_logger defaultLogger
func init() {
// default_logger = log.New(os.Stdout, "\r\n", 0)
default_logger = defaultLogger{log.New(os.Stdout, "\r\n", 0)}
}
2013-11-11 11:48:31 +04:00
func (s *Chain) print(level string, v ...interface{}) {
if s.d.log_mode || s.debug_mode || level == "debug" {
if _, ok := s.d.logger.(Logger); !ok {
fmt.Println("logger haven't been set, using os.Stdout")
2013-11-11 13:16:15 +04:00
s.d.logger = default_logger
2013-11-11 11:48:31 +04:00
}
args := []interface{}{level}
2013-11-11 13:16:15 +04:00
s.d.logger.(Logger).Print(append(args, v...)...)
2013-11-11 05:05:14 +04:00
}
}
2013-11-11 11:48:31 +04:00
func (s *Chain) warn(v ...interface{}) {
go s.print("warn", v...)
2013-11-11 07:53:56 +04:00
}
2013-11-13 20:03:31 +04:00
func (s *Chain) info(v ...interface{}) {
go s.print("info", v...)
}
2013-11-11 11:48:31 +04:00
func (s *Chain) slog(sql string, t time.Time, vars ...interface{}) {
2013-11-11 13:16:15 +04:00
go s.print("sql", time.Now().Sub(t), sql, vars)
2013-11-11 05:05:14 +04:00
}
2013-11-11 11:48:31 +04:00
func (s *Chain) debug(v ...interface{}) {
go s.print("debug", v...)
2013-11-11 05:05:14 +04:00
}