6 Star 11 Fork 1

distill/distill-infra

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
log.go 5.97 KB
一键复制 编辑 原始数据 按行查看 历史
胡正阳 提交于 2021-08-04 21:20 . update logger for custom fields
package log
import (
"context"
"gitee.com/banyanhouse/distill-infra"
conf "gitee.com/banyanhouse/distill-infra/config"
infrautils "gitee.com/banyanhouse/distill-infra/utils"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
"github.com/tietang/go-utils"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
"os"
"path"
"path/filepath"
"time"
)
var (
lfh *utils.LineNumLogrusHook
gsDebug *log.Entry
gsInfo *log.Entry
gsWarn *log.Entry
gsError func(errorInfos ...string) *log.Entry
gsFatal func(errorInfos ...string) *log.Entry
gsPanic func(errorInfos ...string) *log.Entry
)
func GsDebug() *log.Entry {
return gsDebug
}
func GsInfo() *log.Entry {
return gsInfo
}
func GsWarn() *log.Entry {
return gsWarn
}
func GsError() func(errorInfos ...string) *log.Entry {
return gsError
}
func GsFatal() func(errorInfos ...string) *log.Entry {
return gsFatal
}
func GsPanic() func(errorInfos ...string) *log.Entry {
return gsPanic
}
func init() {
// 日志级别
level := os.Getenv("log.debug")
if level == "true" {
log.SetLevel(log.DebugLevel)
}
//开启调用函数、文件、代码行信息的输出
log.SetReportCaller(true)
}
//初始化log配置,配置logrus日志文件滚动生成和
func InitLog(conf *conf.TomlConfig) {
var (
err error
level log.Level
maxAge time.Duration
rotationTime time.Duration
formatter log.Formatter
)
format := conf.Log.Format
if format == "text" {
//设置日志文件输出的日志格式
formatter = &prefixed.TextFormatter{} // 这个是第三方的插件
realFormatter := formatter.(*prefixed.TextFormatter)
realFormatter.FullTimestamp = true
realFormatter.TimestampFormat = "2006-01-02T15:04:05.000000"
// 控制台高亮显示
realFormatter.ForceColors = true
realFormatter.DisableColors = false
realFormatter.ForceFormatting = true // 强制格式化
realFormatter.SetColorScheme(&prefixed.ColorScheme{
InfoLevelStyle: "green",
WarnLevelStyle: "yellow",
ErrorLevelStyle: "red",
FatalLevelStyle: "red",
PanicLevelStyle: "red",
DebugLevelStyle: "gray",
PrefixStyle: "cyan",
TimestampStyle: "37", //"black+h",
})
log.SetFormatter(realFormatter)
} else if format == "json" {
//设置日志文件输出的日志格式
formatter = &log.JSONFormatter{
FieldMap: log.FieldMap{
log.FieldKeyMsg: "message",
},
} // 这个是第三方的插件
realFormatter := formatter.(*log.JSONFormatter)
realFormatter.TimestampFormat = "2006-01-02T15:04:05.000000"
log.SetFormatter(realFormatter)
/*log.WithFields(log.Fields{
"production": conf.App.Name,
})*/
gsDebug = log.WithFields(log.Fields{
"production": conf.App.Name,
})
gsInfo = log.WithFields(log.Fields{
"production": conf.App.Name,
})
gsWarn = log.WithFields(log.Fields{
"production": conf.App.Name,
})
gsError = func(errorInfos ...string) *log.Entry {
return log.WithFields(log.Fields{
"production": conf.App.Name,
"error_type": errorInfos[0],
"error_msg": errorInfos[1],
"error_stacktrace": errorInfos[2],
})
}
gsFatal = func(errorInfos ...string) *log.Entry {
return log.WithFields(log.Fields{
"production": conf.App.Name,
"error_type": errorInfos[0],
"error_msg": errorInfos[1],
"error_stacktrace": errorInfos[2],
})
}
gsPanic = func(errorInfos ...string) *log.Entry {
return log.WithFields(log.Fields{
"production": conf.App.Name,
"error_type": errorInfos[0],
"error_msg": errorInfos[1],
"error_stacktrace": errorInfos[2],
})
}
}
//设置日志输出级别
level, err = log.ParseLevel(conf.Log.Level)
if err != nil {
level = log.InfoLevel
}
log.SetLevel(level)
lfh = utils.NewLineNumLogrusHook()
if conf.Log.OutPut == "file" {
lfh.EnableFileNameLog = true
lfh.EnableFuncNameLog = true
log.AddHook(lfh)
//配置日志输出目录
logDir := conf.Log.Dir
//logTestDir := conf.Log.TestDir
logFilePath, _ := filepath.Abs(logDir)
log.Infof("log dir: %s", logFilePath)
log.Infof("log dir: %s", logFilePath)
err = os.MkdirAll(logDir, os.ModePerm)
if err != nil {
log.Errorf("mkdir %s failed.", logDir)
}
maxAgeStr := conf.Log.MaxAge
maxAge, err = time.ParseDuration(maxAgeStr)
if err != nil {
maxAge = time.Hour * 24
}
rotationTimeStr := conf.Log.RotationTime
rotationTime, err = time.ParseDuration(rotationTimeStr)
if err != nil {
rotationTime = time.Hour
}
//baseLogPath := path.Join(logDir, logFileName)
programName := infrautils.ProgramName() // "distill-infra.log"
mainLogName := programName + ".log"
mainLogLinkPath := path.Join(logDir, mainLogName)
rotationLogNameFormat := programName + ".%Y%m%d%H.log"
log.Warnf("rotationLogNameFormat:%s", rotationLogNameFormat)
logFileFullPath := path.Join(logDir, rotationLogNameFormat)
log.Warnf("logFileFullPath:%s", logFileFullPath)
//设置滚动日志输出writer
rotateWriter, err := rotatelogs.New(
logFileFullPath,
rotatelogs.WithClock(rotatelogs.Local), // 设置时区
rotatelogs.WithLinkName(mainLogLinkPath), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(maxAge), // 文件最大保存时间
rotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔
)
if err != nil {
log.Errorf("config local file system logger error. %+v", err)
}
log.AddHook(lfshook.NewHook(
lfshook.WriterMap{
log.InfoLevel: rotateWriter,
log.ErrorLevel: rotateWriter,
log.DebugLevel: rotateWriter, // 为不同级别设置不同的输出目的
log.WarnLevel: rotateWriter,
log.FatalLevel: rotateWriter,
log.PanicLevel: rotateWriter,
},
formatter,
))
} else {
lfh.EnableFileNameLog = false
lfh.EnableFuncNameLog = false
}
}
type LoggerStarter struct {
infra.BaseStarter
}
func (l *LoggerStarter) Setup(ctx context.Context) {
InitLog(infra.Props(ctx))
log.Info("测试")
log.Debug("测试debug")
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/banyanhouse/distill-infra.git
git@gitee.com:banyanhouse/distill-infra.git
banyanhouse
distill-infra
distill-infra
v0.0.21

搜索帮助

0d507c66 1850385 C8b1a773 1850385