Skip to content

Commit

Permalink
添加日志中间件logrus
Browse files Browse the repository at this point in the history
  • Loading branch information
xhaoxiong committed May 12, 2020
1 parent 4e6c334 commit 21b2f31
Show file tree
Hide file tree
Showing 11 changed files with 562 additions and 322 deletions.
59 changes: 59 additions & 0 deletions commands/new/commom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @Author: xiaoxiao
* @Description:
* @File: commom
* @Version: 1.0.0
* @Date: 2020/5/12 2:12 下午
*/
package commands


var common = `
package controllers
import "github.com/kataras/iris/v12"
type Common struct {
Ctx iris.Context
}
func (this *Common) ReturnJson(status int, message string, args ...interface{}) {
result := make(map[string]interface{})
result["code"] = status
result["message"] = message
key := ""
for _, arg := range args {
switch arg.(type) {
case string:
key = arg.(string)
default:
result[key] = arg
}
}
this.Ctx.JSON(result)
this.Ctx.StopExecution()
return
}
func (this *Common) ReturnSuccess(args ...interface{}) {
result := make(map[string]interface{})
result["code"] = 10000
result["message"] = "success"
key := ""
for _, arg := range args {
switch arg.(type) {
case string:
key = arg.(string)
default:
result[key] = arg
}
}
this.Ctx.JSON(result)
this.Ctx.StopExecution()
return
}
`
23 changes: 23 additions & 0 deletions commands/new/conf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @Author: xiaoxiao
* @Description:
* @File: conf
* @Version: 1.0.0
* @Date: 2020/5/12 2:10 下午
*/
package commands

var conf = `gormlog: true
app_name: "irisgo"
mysql:
username: "root"
password: ""
addr: "127.0.0.1:3306"
name: ""
log:
logger_level: DEBUG #
logger_file: log
with_max_age: 7*24h #文件最大保存时间
with_rotation_count: 5 #设置文件清理前最多保存的个数。
with_rotation_time: 24h #日志切割时间间隔
addr: ":8080"`
106 changes: 106 additions & 0 deletions commands/new/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* @Author: xiaoxiao
* @Description:
* @File: config
* @Version: 1.0.0
* @Date: 2020/5/12 2:11 下午
*/
package commands

var config = `package config
import (
nested "github.com/antonfisher/nested-logrus-formatter"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io"
"log"
"os"
"strings"
"time"
)
type Config struct {
Name string
}
func Init(cfg string) error {
c := Config{
Name: cfg,
}
if err := c.initConfig(); err != nil {
return err
}
initLog()
return nil
}
func (c *Config) initConfig() error {
if c.Name != "" {
viper.SetConfigFile(c.Name)
} else {
viper.AddConfigPath("conf")
viper.SetConfigName("config")
}
viper.SetConfigType("yaml")
viper.AutomaticEnv()
viper.SetEnvPrefix("irisgo")
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
return err
}
return nil
}
func initLog() {
WithMaxAge := viper.GetDuration("log.with_max_age")
WithRotationTime := viper.GetDuration("log.with_rotation_time")
WithRotationCount := viper.GetInt("log.with_rotation_count")
LogName := viper.GetString("log.logger_file")
writer, err := rotatelogs.New(
LogName+".%Y%m%d%H%M",
rotatelogs.WithLinkName(LogName), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(WithMaxAge), // 文件最大保存时间
rotatelogs.WithRotationTime(WithRotationTime), // 日志切割时间间隔
rotatelogs.WithRotationCount(WithRotationCount), //设置文件清理前最多保存的个数。
)
writer1 := os.Stdout
if err!=nil{
log.Fatalf("create file log failed:%v", err)
}
/**
设置日志输入在文件
writer2, err := os.OpenFile(LogName, os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC, 0755)
if err != nil {
log.Fatalf("create file log.txt failed:%v", err)
}*/
//设置在输出日志中添加文件名和方法信息
//logrus.SetReportCaller(true)
//设置输出写入
logrus.SetOutput(io.MultiWriter(writer, writer1))
logrus.SetLevel(logrus.DebugLevel)
//可设置json,txt,nested(需要引入github.com/antonfisher/nested-logrus-formatter)等格式
//logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetFormatter(&nested.Formatter{
FieldsOrder: []string{"component", "category"},
HideKeys: false, //是否隐藏键值
NoColors: false, //是否显示颜色
NoFieldsColors: false,
ShowFullLevel: false,
TrimMessages: false,
CallerFirst: false,
CustomCallerFormatter: nil,
TimestampFormat: time.RFC3339, //格式化时间
})
}
`
25 changes: 25 additions & 0 deletions commands/new/controllers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @Author: xiaoxiao
* @Description:
* @File: controllers
* @Version: 1.0.0
* @Date: 2020/5/12 2:11 下午
*/
package commands

var controllers = `package controllers
import "github.com/kataras/iris/v12"
type TestController struct {
Ctx iris.Context
Common
}
func NewTestController() *TestController {
return &TestController{}
}
func (this *TestController) Get() {
this.ReturnSuccess()
}`
103 changes: 103 additions & 0 deletions commands/new/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* @Author: xiaoxiao
* @Description:
* @File: init
* @Version: 1.0.0
* @Date: 2020/5/12 2:11 下午
*/
package commands

var mysqlInit = `package models
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"github.com/spf13/viper"
"time"
)
type Database struct {
Mysql *gorm.DB
}
var DB *Database
func (db *Database) Init() {
DB = &Database{
Mysql: GetDB(),
}
}
func GetDB() *gorm.DB {
return openMysqlDB(viper.GetString("mysql.username"),
viper.GetString("mysql.password"),
viper.GetString("mysql.addr"),
viper.GetString("mysql.name"))
}
func openMysqlDB(username, password, addr, name string) *gorm.DB {
config := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=%t&loc=%s",
username,
password,
addr,
name,
true,
//"Asia/Shanghai"),
"Local")
db, err := gorm.Open("mysql", config)
if err != nil {
log.Println(err, "Database connection failed. Database name: %s", name)
}
// set for db connection
setupDB(db)
go keepAlive(db)
return db
}
func setupDB(db *gorm.DB) {
db.LogMode(viper.GetBool("gormlog"))
//db.DB().SetMaxOpenConns(20000) // 用于设置最大打开的连接数,默认值为0表示不限制.设置最大的连接数,可以避免并发太高导致连接mysql出现too many connections的错误。
db.DB().SetMaxIdleConns(2) // 用于设置闲置的连接数.设置闲置的连接数则当开启的一个连接使用完成后可以放在池里等候下一次使用。
db.SingularTable(true) //设置表名不为负数
autoMigrate(db)
}
func autoMigrate(db *gorm.DB) {
if err := db.AutoMigrate().Error;
err != nil {
log.Println("自动建表失败", err)
}
}
func keepAlive(dbc *gorm.DB) {
for {
dbc.DB().Ping()
time.Sleep(60 * time.Second)
}
}
`

var traceLogger = `package models
import "time"
type TraceLogger struct {
ReqTime time.Time
ReqUri string
ReqMethod string
Proto string
UserAgent string
Referer string
Length int64
}
func NewLogger() *TraceLogger {
return &TraceLogger{}
}`
Loading

0 comments on commit 21b2f31

Please sign in to comment.