4

go客户之日志_zzxiaoma的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_3764469/5687315
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go客户之日志

精选 原创

zzxiaoma 2022-09-19 09:35:39 博主文章分类:go ©著作权

文章标签 github 文件名 第三方库 文章分类 Go语言 编程语言 私藏项目实操分享 阅读数167

日志采用第三方库github.com/sirupsen/logrus

package logger

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

var Log = logrus.New()
func init() {
ConfigLocalFileSystemLogger("logs/", "cus", time.Hour*24*365, time.Hour*24*30)
}
func ConfigLocalFileSystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
baseLogPaht := path.Join(logPath, logFileName)
writer, err := rotatelogs.New(
baseLogPaht+".%Y%m%d%H%M",
rotatelogs.WithLinkName(baseLogPaht),
rotatelogs.WithMaxAge(maxAge),
rotatelogs.WithRotationTime(rotationTime),
)
if err != nil {
Log.Errorf("config local file system logger error", err)
}
Log.SetLevel(logrus.DebugLevel)
lfHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer, // 为不同级别设置不同的输出目的
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
logrus.FatalLevel: writer,
logrus.PanicLevel: writer,
}, &logrus.TextFormatter{DisableColors: true})
Log.AddHook(lfHook)
}

ConfigLocalFileSystemLogger("logs/", "cus", time.Hour*24*365, time.Hour*24*30)方法用于对日志进行设置,第一个参数是存放路径,第二个是文件名,第三个是存放最长时间,第四个参数是文件多长时间生成一个。这样就可以30天生成一个文件,1年以前的文件自动删除。文件名为cus开头后面是时间字符串。

使用方法:logger是包,Log是上面文件定义的对象,var Log = logrus.New(),使用Error方法存储错误。

logger.Log.Error(err)

具体logrus的详细用法可以查看我的另一篇文章。

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK