Skip to content

Commit

Permalink
增加gorm 和日志切割
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonkti committed Aug 12, 2020
1 parent 07c7c0b commit 1554d50
Show file tree
Hide file tree
Showing 15 changed files with 371 additions and 52 deletions.
16 changes: 16 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
APP_ENV=local
APP_DEBUG=true
APP_NAME=test
APP_PORT=8080

DB_CONNECTION=mysql
DB_HOST=192.168.10.10
DB_PORT=3306
DB_DATABASE=homestead
DB_PARAMS="parseTime=true&loc=Local"
DB_USERNAME=homestead
DB_PASSWORD=secret

JWT_SecretKey=test
JWT_EXP=480

8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/iris-framework.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/Repository/UserRepository.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type UserRepository struct {

func (userService *UserRepository) QueryByUsername(username string) (Models.User, error) {
var user = Models.User{
ID: 1,
Username: username,
}
has, err := userService.db.Get(&user)
Expand Down
19 changes: 19 additions & 0 deletions config/Log/MineFormatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package config

import (
"fmt"
"github.com/sirupsen/logrus"
"strings"
"time"
)

type MineFormatter struct{}

const TimeFormat = "2006-01-02 15:04:05"

func (s *MineFormatter) Format(entry *logrus.Entry) ([]byte, error) {

msg := fmt.Sprintf("[%s] [%s] %s\n", time.Now().Local().Format(TimeFormat), strings.ToUpper(entry.Level.String()), entry.Message)

return []byte(msg), nil
}
2 changes: 1 addition & 1 deletion config/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
var once sync.Once
var DB *xorm.Engine

func init() {
func initXorm() {
once.Do(func() {
dbDriver := os.Getenv("DB_CONNECTION")
switch dbDriver {
Expand Down
66 changes: 66 additions & 0 deletions config/gorm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package config

import (
"IrisFramework/app/Models"
"errors"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm"
log "github.com/sirupsen/logrus"
"os"
)

type GormLogger struct{}
var Gorm *gorm.DB

func initDB() {
once.Do(func() {
dbDriver := os.Getenv("DB_CONNECTION")
switch dbDriver {
case "mysql":
initMysql()
break
default:
panic(errors.New("only supper mysql"))
break
}
})

}

/**
初始化mysql
*/
func initMysql() {
db, err := gorm.Open("mysql", "homestead:secret@(192.168.10.10:3306)/homestead?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
defer db.Close()

db.SetLogger(&GormLogger{})
db.LogMode(true)
db.SingularTable(true)

// test
Gorm = db

var userModel Models.User
Gorm.Where("username like ?","%风%").Find(&userModel)
}


/**
打印日志
*/
func (*GormLogger) Print(v ...interface{}) {

switch v[0] {
case "sql":
// [gorm] [sql] SELECT * FROM `user` WHERE `user`.`deleted_at` IS NULL AND ((username like ?)) []interface {}{"%萧风%"} [1.880301ms]
msg := fmt.Sprintf("[%s] [%s] [%s] %s %#v ", "gorm", v[0], v[2], v[3], v[4])
Log.Info(msg)
case "log":
log.WithFields(log.Fields{"module": "gorm", "type": "log"}).Print(v[2])
}
}
11 changes: 11 additions & 0 deletions config/inits.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package config

func init() {
// 初始化日志
InitLog()
// 初始化 数据库
initDB()

//initXorm()

}
67 changes: 67 additions & 0 deletions config/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package config

import (
config "IrisFramework/config/Log"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"os"
"path"
"time"
)

const LogPath = "./storage/logs"
const FileSuffix = ".log"

var Log = logrus.New()

func InitLog() {
Log.Out = os.Stdout
var loglevel logrus.Level
err := loglevel.UnmarshalText([]byte("info"))
if err != nil {
Log.Panicf("设置log级别失败:%v", err)
}

Log.SetLevel(loglevel)

NewSimpleLogger(Log, LogPath, 8)
}

/**
文件日志
*/
func NewSimpleLogger(log *logrus.Logger, logPath string, save uint) {

lfHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer(logPath, "debug", save), // 为不同级别设置不同的输出目的
logrus.InfoLevel: writer(logPath, "info", save),
logrus.WarnLevel: writer(logPath, "warn", save),
logrus.ErrorLevel: writer(logPath, "error", save),
logrus.FatalLevel: writer(logPath, "fatal", save),
logrus.PanicLevel: writer(logPath, "panic", save),
}, &config.MineFormatter{})

log.AddHook(lfHook)
}

/**
文件设置
*/
func writer(logPath string, level string, save uint) *rotatelogs.RotateLogs {
logFullPath := path.Join(logPath, level)
var cstSh, _ = time.LoadLocation("Asia/Shanghai") //上海
fileSuffix := time.Now().In(cstSh).Format("2006-01-02") + FileSuffix

logier, err := rotatelogs.New(
logFullPath+"-"+fileSuffix,
rotatelogs.WithLinkName(logFullPath), // 生成软链,指向最新日志文件
rotatelogs.WithRotationCount(int(save)), // 文件最大保存份数
rotatelogs.WithRotationTime(time.Hour*24), // 日志切割时间间隔
)

if err != nil {
panic(err)
}
return logier
}
27 changes: 26 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,37 @@ module IrisFramework
go 1.13

require (
github.com/go-sql-driver/mysql v1.4.1
github.com/ajg/form v1.5.1 // indirect
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/go-sql-driver/mysql v1.5.0
github.com/google/go-querystring v1.0.0 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/iris-contrib/middleware/cors v0.0.0-20191219204441-78279b78a367
github.com/iris-contrib/middleware/jwt v0.0.0-20191219204441-78279b78a367
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jinzhu/gorm v1.9.15
github.com/joho/godotenv v1.3.0
github.com/jonboulle/clockwork v0.2.0 // indirect
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/kataras/iris/v12 v12.1.7
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 // indirect
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/mattn/go-colorable v0.1.7 // indirect
github.com/moul/http2curl v1.0.0 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sergi/go-diff v1.1.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/sirupsen/logrus v1.2.0
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/tebeka/strftime v0.1.5 // indirect
github.com/valyala/fasthttp v1.15.1 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
xorm.io/core v0.7.3
xorm.io/xorm v0.8.1
)
Loading

0 comments on commit 1554d50

Please sign in to comment.