gin框架使用logrus日志模块

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!!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值