可以使用logrus的hook,下面是我的代码,日志打印到项目根目录的logs文件夹下,需要提前执行命令安装第三方库
go get -u github.com/rifflock/lfshook
go get -u github.com/lestrrat-go/file-rotatelogs
然后再使用formatter时关闭颜色输出,完整的文件如下
package base
import (
"time"
"github.com/rifflock/lfshook"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
)
func init() {
// 命令行日志格式
stdFormatter := &prefixed.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02.15:04:05.000000",
ForceFormatting: true,
ForceColors: true,
DisableColors: false,
}
log.SetFormatter(stdFormatter)
// 日志级别
log.SetLevel(log.DebugLevel)
// 日志文件和滚动配置
writer, err := rotatelogs.New(
"logs/console.log"+".%Y%m%d%H%M",
//rotatelogs.WithLinkName("logs/console.log"), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(7*24*time.Hour), // 文件最大保存时间
rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
)
if err != nil {
log.Errorf("config local file system logger error. %v", errors.WithStack(err))
}
// 文件输出格式
fileFormatter := &prefixed.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02.15:04:05.000000",
ForceFormatting: true,
ForceColors: false,
DisableColors: true,
}
lfHook := lfshook.NewHook(lfshook.WriterMap{
log.InfoLevel: writer,
log.ErrorLevel: writer,
}, fileFormatter)
log.AddHook(lfHook)
log.Info("测试")
log.Debug("测试")
}