Browse Source

Set logger to global variable

main
Granty1 5 years ago
parent
commit
35eb20f730
  1. 4
      QMPlusServer/cmd/windows.go
  2. 6
      QMPlusServer/init/initRedis/init_redis.go
  3. 14
      QMPlusServer/init/initRouter/init_router.go
  4. 9
      QMPlusServer/init/initlog/qmlog/log.go
  5. 4
      QMPlusServer/init/qmsql/initMysql.go
  6. 4
      QMPlusServer/init/registTable/regist_table.go
  7. 14
      QMPlusServer/main.go
  8. 2
      QMPlusServer/middleware/cors.go
  9. 6
      QMPlusServer/middleware/logger.go
  10. 6
      QMPlusServer/static/config/config.json

4
QMPlusServer/cmd/windows.go

@ -9,7 +9,7 @@ import (
"time"
)
func RunWindowsServer(Router *gin.Engine, logger log.Logger) {
func RunWindowsServer(Router *gin.Engine) {
address := fmt.Sprintf(":%d", config.GinVueAdminconfig.System.Addr)
s := &http.Server{
Addr: address,
@ -19,7 +19,7 @@ func RunWindowsServer(Router *gin.Engine, logger log.Logger) {
MaxHeaderBytes: 1 << 20,
}
time.Sleep(10 * time.Microsecond)
logger.Debug("server run success on ", address)
log.L.Debug("server run success on ", address)
fmt.Printf(`欢迎使用 Gin-Vue-Admin
作者奇淼 And Spike666

6
QMPlusServer/init/initRedis/init_redis.go

@ -8,7 +8,7 @@ import (
var DEFAULTREDIS *redis.Client
func InitRedis(logger log.Logger) (client *redis.Client) {
func InitRedis() (client *redis.Client) {
client = redis.NewClient(&redis.Options{
Addr: config.GinVueAdminconfig.RedisAdmin.Addr,
Password: config.GinVueAdminconfig.RedisAdmin.Password, // no password set
@ -16,9 +16,9 @@ func InitRedis(logger log.Logger) (client *redis.Client) {
})
pong, err := client.Ping().Result()
if err != nil {
logger.Error(err)
log.L.Error(err)
} else {
logger.Info("redis connect ping response:", pong)
log.L.Info("redis connect ping response:", pong)
DEFAULTREDIS = client
}
return client

14
QMPlusServer/init/initRouter/init_router.go

@ -11,18 +11,18 @@ import (
)
//初始化总路由
func InitRouter(logger log.Logger) *gin.Engine {
func InitRouter() *gin.Engine {
var Router = gin.Default()
//Router.Use(middleware.LoadTls()) // 打开就能玩https了
// 如果不需要日志 请关闭这里
Router.Use(middleware.LoggerMiddlewareFactory(logger))
logger.Debug("use middleware logger")
Router.Use(middleware.Logger())
log.L.Debug("use middleware logger")
// 跨域
Router.Use(middleware.CorsMiddlewareFactory())
logger.Debug("use middleware cors")
Router.Use(middleware.Cors())
log.L.Debug("use middleware cors")
Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
logger.Debug("register swagger handler")
log.L.Debug("register swagger handler")
// 方便统一添加路由组前缀 多服务器上线使用
ApiGroup := Router.Group("")
router.InitUserRouter(ApiGroup) // 注册用户路由
@ -36,6 +36,6 @@ func InitRouter(logger log.Logger) *gin.Engine {
router.InitJwtRouter(ApiGroup) // jwt相关路由
router.InitSystemRouter(ApiGroup) // system相关路由
router.InitCustomerRouter(ApiGroup) // 客户路由
logger.Info("router register success")
log.L.Info("router register success")
return Router
}

9
QMPlusServer/init/initlog/qmlog/log.go

@ -22,7 +22,7 @@ const (
)
var (
configNotFound = errors.New("logger config not found")
configNotFound = errors.New("logger prefix not found")
defaultFormatter = `%{time:2006/01/02 - 15:04:05.000} %{longfile} %{color:bold}▶ [%{level:.6s}] %{message}%{color:reset}`
)
@ -31,8 +31,11 @@ type Logger struct{
logger *oplogging.Logger
}
func NewLogger() (log.Logger, error) {
func NewLogger() error {
c := config.GinVueAdminconfig.Log
if c.Prefix == "" {
return configNotFound
}
logger := oplogging.MustGetLogger(module)
var backends []oplogging.Backend
backends = registerStdout(c, backends)
@ -40,7 +43,7 @@ func NewLogger() (log.Logger, error) {
oplogging.SetBackend(backends...)
log.SetLogger(logger)
return logger, nil
return nil
}
func registerStdout(c config.Log, backends []oplogging.Backend) []oplogging.Backend {

4
QMPlusServer/init/qmsql/initMysql.go

@ -10,9 +10,9 @@ import (
var DEFAULTDB *gorm.DB
//初始化数据库并产生数据库全局变量
func InitMysql(admin config.MysqlAdmin, logger log.Logger) *gorm.DB {
func InitMysql(admin config.MysqlAdmin) *gorm.DB {
if db, err := gorm.Open("mysql", admin.Username+":"+admin.Password+"@("+admin.Path+")/"+admin.Dbname+"?"+admin.Config); err != nil {
logger.Error("DEFAULTDB数据库启动异常",err)
log.L.Error("DEFAULTDB数据库启动异常",err)
} else {
DEFAULTDB = db
DEFAULTDB.DB().SetMaxIdleConns(10)

4
QMPlusServer/init/registTable/regist_table.go

@ -8,7 +8,7 @@ import (
)
//注册数据库表专用
func RegistTable(db *gorm.DB, logger log.Logger) {
func RegistTable(db *gorm.DB) {
db.AutoMigrate(sysModel.SysUser{},
sysModel.SysAuthority{},
sysModel.SysMenu{},
@ -22,5 +22,5 @@ func RegistTable(db *gorm.DB, logger log.Logger) {
dbModel.ExaFileChunk{},
dbModel.ExaCustomer{},
)
logger.Debug("register table success")
log.L.Debug("register table success")
}

14
QMPlusServer/main.go

@ -21,23 +21,21 @@ import (
// @BasePath /
func main() {
var err error
logger, err := qmlog.NewLogger()
if err != nil {
if err:= qmlog.NewLogger(); err != nil {
fmt.Println(err)
}
// 链接初始化数据库
db := qmsql.InitMysql(config.GinVueAdminconfig.MysqlAdmin, logger)
db := qmsql.InitMysql(config.GinVueAdminconfig.MysqlAdmin)
if config.GinVueAdminconfig.System.UseMultipoint {
// 初始化redis服务
_ = initRedis.InitRedis(logger)
_ = initRedis.InitRedis()
}
// 注册数据库表
registTable.RegistTable(db, logger)
registTable.RegistTable(db)
// 程序结束前关闭数据库链接
defer qmsql.DEFAULTDB.Close()
// 注册路由
Router := initRouter.InitRouter(logger)
Router := initRouter.InitRouter()
//Router.RunTLS(":443","ssl.pem", "ssl.key") // https支持 需要添加中间件
//sysType := runtime.GOOS
//
@ -47,6 +45,6 @@ func main() {
//}
//if sysType == "windows" {
// WIN系统
cmd.RunWindowsServer(Router, logger)
cmd.RunWindowsServer(Router)
//}
}

2
QMPlusServer/middleware/cors.go

@ -6,7 +6,7 @@ import (
)
// 处理跨域请求,支持options访问
func CorsMiddlewareFactory() gin.HandlerFunc {
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")

6
QMPlusServer/middleware/logger.go

@ -10,7 +10,7 @@ import (
"github.com/gin-gonic/gin"
)
func LoggerMiddlewareFactory(logger log.Logger) gin.HandlerFunc {
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
// request time
start := time.Now()
@ -27,7 +27,7 @@ func LoggerMiddlewareFactory(logger log.Logger) gin.HandlerFunc {
// copy request content
req, _ := httputil.DumpRequest(c.Request, true)
if logFlag {
logger.Debug(
log.L.Debug(
"Request:", method, clientIP, path, string(req))
}
// replace writer
@ -44,7 +44,7 @@ func LoggerMiddlewareFactory(logger log.Logger) gin.HandlerFunc {
latency := end.Sub(start)
statusCode := c.Writer.Status()
if logFlag {
logger.Debug(
log.L.Debug(
"Response:",
statusCode,
latency,

6
QMPlusServer/static/config/config.json

@ -30,11 +30,5 @@
"keyLong": 6,
"imgWidth": 120,
"imgHeight": 40
},
"log": {
"prefix": "[GIN-VUE-ADMIN]",
"logFile": false,
"stdout": ["DEBUG"],
"file": ["WARNING"]
}
}
Loading…
Cancel
Save