Go iris 日志文件的分割
iris 官方案例只给了文件日志,但没有给日志分割的方法,一旦访问量过大,日志文件就成吨成吨的,这很让我苦恼。经研究使用 github.com/lestrrat-go/file-rotatelogs 包可解决,代码如下:
package main
import (
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"os"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/logger"
)
func main() {
app := iris.New()
path := "iris"
writer, _ := rotatelogs.New(
path+"%Y%m%d%H%M.log",
rotatelogs.WithLinkName(path),
rotatelogs.WithMaxAge(time.Duration(180)*time.Second),
//这里设置1分钟产生一个日志文件
rotatelogs.WithRotationTime(time.Duration(60)*time.Second),
)
app.Logger().SetOutput(writer)//日志写入文件
app.Logger().AddOutput(os.Stdout)//日志同时写入控制台,如果不想显示控制台可注释此语句
//记录路由日志
app.Use(logger.New(logger.Config{
Status: true,
IP: true,
Method: true,
Path: true,
Query: true,
LogFunc: nil,
LogFuncCtx: nil,
Skippers: nil,
}))
app.Get("/", func(ctx iris.Context) {
//手动日志
ctx.Application().Logger().Infof("这里产生一个错误,请注意了: %s", ctx.Path())
ctx.WriteString("hello")
})
if err := app.Run(iris.Addr(":8080")); err != nil {
app.Logger().Warn("Shutdown with error: " + err.Error())
}
}
浙公网安备 33010602011771号