pkg/logger/logger.go
package logger
import (
"bytes"
"fmt"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/sirupsen/logrus"
"path/filepath"
"time"
)
type MyFormatter struct{}
func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
timestamp := entry.Time.Format("2006-01-02 15:04:05")
var newLog string
//需要开启行号信息
if entry.HasCaller() {
fName := filepath.Base(entry.Caller.File)
newLog = fmt.Sprintf("[%s] [%s] [%s:%d %s] %s\n",
timestamp, entry.Level, fName, entry.Caller.Line, entry.Caller.Function, entry.Message)
} else {
newLog = fmt.Sprintf("[%s] [%s] %s\n", timestamp, entry.Level, entry.Message)
}
b.WriteString(newLog)
return b.Bytes(), nil
}
func init() {
logPath := "logs/gateway"
linkName := "logs/latest.log"
/* 日志轮转相关函数
`WithLinkName` 为最新的日志建立软连接
`WithRotationTime` 设置日志分割的时间,隔多久分割一次
WithMaxAge 和 WithRotationCount二者只能设置一个
`WithMaxAge` 设置文件清理前的最长保存时间
`WithRotationCount` 设置文件清理前最多保存的个数
*/
// 下面配置日志每隔 1 分钟轮转一个新文件,保留最近 3 分钟的日志文件,多余的自动清理掉。
writer, _ := rotatelogs.New(
logPath+"_%Y%m%d.log",
rotatelogs.WithLinkName(linkName),
rotatelogs.WithMaxAge(30*24*time.Hour),
rotatelogs.WithRotationTime(7*24*time.Hour),
)
logrus.SetOutput(writer)
//开启行号信息
logrus.SetReportCaller(true)
// 输出格式
logrus.SetFormatter(&MyFormatter{})
}
// 预留日志单独处理模块
func SetUp() {}
main.go
func init() {
// 日志模块
logger.SetUp()
}
使用
package api
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"net/http"
)
func TestPing(c *gin.Context) {
logrus.Info("hello world!!!!")
c.JSON(http.StatusOK, gin.H{"msg": "pong"})
}
效果
[2023-02-01 17:27:28] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:29] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:29] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:29] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:30] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:30] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!
[2023-02-01 17:27:30] [info] [ping.go:11 algorithmGateway/routers/api.TestPing] hello world!!!!