Skip to content
On this page

基础用法

下载依赖

Go
go get github.com/sirupsen/logrus

输出log

Go
logrus.Errorln("logrus => Error")
logrus.Warningln("logrus => Warn")
logrus.Infoln("logrus => Info")
logrus.Debugln("logrus => Debug")

logrus_1

因为日志等级默认是info等级,所以debug日志未输出

日志等级

  • Panic:记录日志,然后panic

  • Fatal:致命错误,出现错误时程序无法正常运转,输出日志后,程序退出

  • Error:错误日志,需要查看原因

  • Warn:警告信息,提醒程序员注意

  • Info:关键操作,核心流程的日志

  • Debug:一般程序中输出的调试信息

  • Trace:很细粒度的信息,一般用不到

TIP

  • 日志级别从上向下依次增加Trace最大,Panic最小

  • logrus有一个日志级别,高于这个级别的日志不会输出。默认的级别为InfoLevel

Go
const (
	PanicLevel Level = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
	TraceLevel
)

获取日志等级

Go
fmt.Println(logrus.GetLevel()) // info

修改日志等级

Go
logrus.SetLevel(logrus.DebugLevel)
logrus.Errorln("logrus => Error")
logrus.Warningln("logrus => Warn")
logrus.Infoln("logrus => Info")
logrus.Debugln("logrus => Debug")
fmt.Println(logrus.GetLevel())

logrus_2

输出日志添加额外字段

添加单个字段

Go
logrus.SetLevel(logrus.DebugLevel)
logInstance := logrus.WithField("name", "如燕")
logInstance.Errorln("logInstance => Error")
logInstance.Warningln("logInstance => Warn")
logInstance.Infoln("logInstance => Info")
logInstance.Debugln("logInstance => Debug")

/**
ERRO[0000] logInstance => Error                          name="如燕"
WARN[0000] logInstance => Warn                           name="如燕"
INFO[0000] logInstance => Info                           name="如燕"
DEBU[0000] logInstance => Debug                          name="如燕"
*/

同时添加多个字段

Go
logrus.SetLevel(logrus.DebugLevel)
logInstance := logrus.WithFields(logrus.Fields{
    "name": "如燕",
    "age":  18,
})
logInstance.Errorln("logInstance => Error")
logInstance.Warningln("logInstance => Warn")
logInstance.Infoln("logInstance => Info")
logInstance.Debugln("logInstance => Debug")

/**
ERRO[0000] logInstance => Error                          age=18 name="如燕"
WARN[0000] logInstance => Warn                           age=18 name="如燕"
INFO[0000] logInstance => Info                           age=18 name="如燕"
DEBU[0000] logInstance => Debug                          age=18 name="如燕"
*/

设置日志展示调用文件路径、行数、函数名称

Go
logrus.SetReportCaller(true)

实现原理如下:

Go
caller := ""
if entry.HasCaller() {
    funcVal := fmt.Sprintf("%s()", entry.Caller.Function)
    fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)

    if f.CallerPrettyfier != nil {
        funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
    }

    if fileVal == "" {
        caller = funcVal
    } else if funcVal == "" {
        caller = fileVal
    } else {
        caller = fileVal + " " + funcVal
    }
}

设置日志格式

  • 内置两种格式JSONFormatter(JSON 格式)TextFormatter(文本格式)

修改日志为json格式

Go
logrus.SetFormatter(&logrus.JSONFormatter{}) // 设置为json格式
logrus.SetFormatter(&logrus.TextFormatter{}) // 设置为json格式
logInstance := logrus.WithFields(logrus.Fields{
    "name": "如燕",
    "age":  18,
})
logInstance.Infoln("info")

// {"age":18,"level":"info","msg":"info","name":"如燕","time":"2023-08-02T22:02:05+08:00"}

JSONFormatter/TextFormatter中可传的一些配置如下:

  • ForceColors:是否强制使用颜色输出

  • DisableColors:是否禁用颜色输出

  • ForceQuote:是否强制引用所有值

  • DisableQuote:是否禁用引用所有值

  • DisableTimestamp:是否禁用时间戳记录

  • FullTimestamp:是否在输出完整的时间戳

  • TimestampFormat:用于输出完整时间戳的时间戳格式

将日志输出到日志文件中

Go
func outputFile() {
	file, _ := os.OpenFile("logs/a.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	writes := []io.Writer{
		file,
		os.Stdout, // 配置这个可以同时将日志输出到控制台上
	}
	outputWrite := io.MultiWriter(writes...)
	logrus.SetOutput(outputWrite)
	logrus.SetFormatter(&logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	logInstance := logrus.WithFields(logrus.Fields{
		"name": "狄仁杰",
		"age":  70,
	})
	logInstance.Infoln("info")
}

自定义颜色

  • Logrus中对不同日志的颜色定义可点击这里查看

如下代码:

Go
fmt.Println("\033[30m 黑色 \033[0m")
  • \033[30m\033[0mANSI转义码,用于在终端输出中设置文本颜色,这两个转义码分别表示设置文本颜色为黑色和重置文本颜色至默认值

  • \033(八进制表示法)转义字符,也可以写成\x1b(十六进制表示法)

  • [30m表示设置文本颜色30黑色的颜色代码

  • \033[0m表示重置文本颜色回到默认值

文本颜色

Go
fmt.Println("\033[30m 黑色文本 \033[0m")
fmt.Println("\033[31m 红色文本 \033[0m")
fmt.Println("\x1b[32m 绿色文本 \x1b[0m")
fmt.Println("\033[33m 黄色文本 \033[0m")
fmt.Println("\033[34m 蓝色文本 \033[0m")
fmt.Println("\x1b[35m 紫色文本 \x1b[0m")
fmt.Println("\033[36m 青色文本 \033[0m")
fmt.Println("\033[37m 灰色文本 \033[0m")

logrus_text_color

文本背景色

Go
fmt.Println("\033[40m 黑色背景 \033[0m")
fmt.Println("\033[41m 红色背景 \033[0m")
fmt.Println("\033[42m 绿色背景 \033[0m")
fmt.Println("\033[43m 黄色背景 \033[0m")
fmt.Println("\033[44m 蓝色背景 \033[0m")
fmt.Println("\033[45m 紫色背景 \033[0m")
fmt.Println("\x1b[46m 青色背景 \x1b[0m")
fmt.Println("\x1b[47m 灰色背景 \x1b[0m")

logrus_bg_color

实现自定义设置输入日志颜色

Go
type Formatter interface {
	Format(*Entry) ([]byte, error)
} 
Go
// 设置一套颜色
const (
	CRed    = 31
	CYellow = 33
	CCyan   = 36
	CPurple = 35
	CGray   = 37
)

type MFormat struct{}

func (m MFormat) Format(entry *logrus.Entry) ([]byte, error) {
	// 设置日志颜色
	var levelColor int
	switch entry.Level {
	case logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel:
		levelColor = CRed
	case logrus.WarnLevel:
		levelColor = CYellow
	case logrus.InfoLevel:
		levelColor = CCyan
	case logrus.DebugLevel:
		levelColor = CPurple
	default:
		levelColor = CGray
	}
	var buffer *bytes.Buffer
	if buffer = entry.Buffer; buffer == nil {
		buffer = &bytes.Buffer{}
	}
	fmt.Fprintf(buffer, "\x1b[%dm[%s]\x1b[0m\n", levelColor, entry.Message)
	return buffer.Bytes(), nil
}

func customLogFormat() {
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetFormatter(&MFormat{})
	logrus.Errorln("自定义颜色 => Error输出")
	logrus.Warningln("自定义颜色 => Warn输出")
	logrus.Infoln("自定义颜色 => Info输出")
	logrus.Debugln("自定义颜色 => Debug输出")
}

logrus_custom_color