Go日志系统
logrus作为go开发的日志系统;
建议采用 log.WithFields 方法以json形式生成日志文件,这样方便ELK日志系统抓取和分析日志。
package seedlog
import (
"encoding/json"
log "github.com/sirupsen/logrus"
)
const SEED_LOG_VERSION = "1.0.0.0"
type SeedLog struct {
//FileName string `json:"FileName"`
FilePath string `json:"FilePath"`
//JsonFormat bool `json:"JsonFormat"`
LogLevel log.Level `json:"LogLevel"`
mLog *log.Logger
}
func (base* SeedLog) GetVersion() string {
data, _ := json.Marshal(struct {
VersionType string
VersionValue string
}{
VersionType:"SEED_LOG_VERSION",
VersionValue:SEED_LOG_VERSION,
})
return string(data)
}
/*
日志使用方式
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
*/
package seedlog
import (
rotelog "github.com/lestrrat-go/file-rotatelogs"
log "github.com/sirupsen/logrus"
"os"
"time"
)
func (base* SeedLog) Init() error{
base.mLog = log.New()
if base.JsonFormat {
base.mLog.SetFormatter(&log.JSONFormatter{})
} else {
base.mLog.SetFormatter(&log.TextFormatter{})
}
if len(base.FilePath) == 0 {
base.mLog.SetOutput(os.Stdout)
} else {
writer, _ := rotelog.New(
base.FilePath+".%Y%m%d%H%M",//日志命名方式
rotelog.WithLinkName(base.FilePath),//保存路径
rotelog.WithMaxAge(time.Duration(7*24)*time.Hour),//文件最大保存时间
rotelog.WithRotationTime(time.Duration(24)*time.Hour), //每隔24h产生新的日志文件
rotelog.WithRotationCount(4), // 日志保留数量
)
log.SetOutput(writer)
}
//日志级别数据
if base.LogLevel < 0 || base.LogLevel > 6 {
base.mLog.SetLevel(log.DebugLevel)
} else {
log.SetLevel(base.LogLevel)
}
return nil
}
func (base* SeedLog) GetLogHandle() *log.Logger {
if base.mLog == nil {
base.mLog = log.New()
base.Init()
}
return base.mLog
}
日志类调用方式:
package main
import "seedlog"
func main() {
var logs seedlog
logs.FilePath="./log/seed_center"
logs.logInit()
logs.GetLogHandle().WithFields(log.Fields{}).Info("server will stop wait 5s...")
return
}