Golang-07 为gin添加logrus日志功能

自定义输出格式
package cclog

import (
    "bytes"
    "fmt"
    "strings"

    "github.com/sirupsen/logrus"
)

type Formatter struct{}

func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
    var out string
    if entry.HasCaller() {
        var pkg bytes.Buffer
        for _, t := range strings.Split(entry.Caller.File, "/") {
                        if len(t) == 0 {
                           continue;
                         }
            pkg.WriteString(t[:1])
            pkg.WriteString(".")
        }
        pkg.WriteString(entry.Caller.Function)

        out = fmt.Sprintf("[%s][%s] %s(%d) %s\n", entry.Level.String()[:4], entry.Time.Format("2006-01-02 15:03:04.000"), pkg.String(), entry.Caller.Line, entry.Message)
    } else {
        out = fmt.Sprintf("[%s][%s] %s\n", entry.Level.String()[:4], entry.Time.Format("2006-01-02 15:03:04.000"), entry.Message)
    }
    return []byte(out), nil
}
配置类

import (
    "time"
    log "github.com/sirupsen/logrus"
    "gopkg.in/natefinch/lumberjack.v2"
    "hello_gin/cclog"
)

func init() {
    log.SetFormatter(new(cclog.Formatter))
    log.SetReportCaller(true)
    log.SetOutput(&lumberjack.Logger{
        Filename:   "./logs/api.log",
        MaxSize:    100, // megabytes
        MaxBackups: 3,
        MaxAge:     28,   // days
        Compress:   true, // disabled by default
    })
    // log.SetOutput(os.Stdout)
    log.SetLevel(log.DebugLevel)
}

func main() {
    r := gin.Default()
    r.GET("/app", handleApp)
    r.Run(":80")
}
func handleApp(c *gin.Context) {
    log.Info("good luck")
    c.JSON(200, gin.H{"code": 300, "msg": "OK"})
}

打印输出:

[info][2019-09-10 15:03:50.330] D.g.s.h.m.main.handleApp(67) good luck

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,719评论 0 3
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,510评论 0 17
  • 在今年颁奖季普遍疲软的情况下,我念念不忘去年的《银翼杀手2049》所带给我的终极审美体验。当时我迟迟下不去手,不知...
    我叫湿湿阅读 2,464评论 6 9
  • 教育局门卫老王,虽然不识字,却喜欢营造文化氛围。 元旦这天,老王娶后老伴儿,求办公室主任写一幅对联,办公室主任爱开...
    若萤若水阅读 852评论 0 3
  • 每一种人生的选择,都有自己的代价与收获,人生的每一条路,无非都是一场戏,不同的选择,经历不同的人生,看到不同的风景...
    默默的路过阅读 188评论 0 1