Go中使用logrus框架将日志保存在文件和控制台输出
- 安装
go get github.com/sirupsen/logrus
go get github.com/lestrrat-go/file-rotatelogs
go get github.com/rifflock/lfshook
- 完整代码
import ("fmt"rotatelogs "github.com/lestrrat-go/file-rotatelogs""github.com/rifflock/lfshook""github.com/sirupsen/logrus""io""os""path""time"
)var LogFile *logrus.Loggerfunc init() {LogFile = loggerToFile()
}// 日志记录到文件
func loggerToFile() *logrus.Logger {logFilePath := "/data/logs"logFileName := "log_info"// 日志文件fileName := path.Join(logFilePath, logFileName)// 写入文件src, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)if err != nil {fmt.Println("err", err)}// 实例化logger := logrus.New()//设置日志级别logger.SetLevel(logrus.InfoLevel)logger.SetReportCaller(true)//设置输出writers := []io.Writer{src,os.Stdout}// Log.Out = srcfileAndStdoutWriter := io.MultiWriter(writers...)if err == nil {logger.SetOutput(fileAndStdoutWriter)} else {logger.Info("failed to log to file.")}// 设置 rotatelogslogWriter, err := rotatelogs.New(// 分割后的文件名称fileName+".%Y%m%d.log",// 生成软链,指向最新日志文件rotatelogs.WithLinkName(fileName),// 设置最大保存时间(30天)rotatelogs.WithMaxAge(30*24*time.Hour),// 设置日志切割时间间隔(1天)rotatelogs.WithRotationTime(24*time.Hour),)writeMap := lfshook.WriterMap{logrus.InfoLevel: logWriter,logrus.FatalLevel: logWriter,logrus.DebugLevel: logWriter,logrus.WarnLevel: logWriter,logrus.ErrorLevel: logWriter,logrus.PanicLevel: logWriter,}lfHook := lfshook.NewHook(writeMap, &logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05",})// 新增 Hooklogger.AddHook(lfHook)return logger
}
- Gin使用
import ("github.com/gin-gonic/gin""github.com/sirupsen/logrus""39ai-http-go/util""time"
)func LogToFileMiddleware(c *gin.Context) {logger := util.LogFile// 开始时间startTime := time.Now()// 处理请求c.Next()// 结束时间endTime := time.Now()// 执行时间latencyTime := endTime.Sub(startTime)// 请求方式reqMethod := c.Request.Method// 请求路由reqUri := c.Request.RequestURI// 状态码statusCode := c.Writer.Status()// 请求IPclientIP := c.ClientIP()// 日志格式logger.WithFields(logrus.Fields{"status_code": statusCode,"latency_time": latencyTime,"client_ip": clientIP,"req_method": reqMethod,"req_uri": reqUri,}).Info()
}
gin中
engine := gin.Default()
engine.Use(middle.LogToFileMiddleware)
- 全局使用
自己封装或者直接使用 var LogFile *logrus.Logger 变量
// 示例
var log = util.LogFilefunc main(){param := "hello"log.Infof("程序启动 %v", param)
}