Logrus 日志框架——自定义日志颜色

Logrus 日志框架——自定义日志颜色

自定义日志颜色,我们需要使用到 github.com/fatih/color 库,github.com/fatih/color是一个Go语言的库,用于在终端中打印带有颜色的文本。

github.com/fatih/color 库提供了一种简单的方式来自定义和添加颜色到终端输出,例如设置前景色、背景色、属性(粗体、下划线等)、样式重置等。我们可以根据需要进行自定义和组合。

安装 color 库

只需要在终端中执行以下命令安装 github.com/fatih/color 库:

 go get "github.com/fatih/color"

使用样例:

使用github.com/fatih/color库实现在终端中打印带有颜色的文本样例如下:

package main

import (
	"github.com/fatih/color"
)

func main() {
    
    
	// 打印红色的文本
	color.Red("This is a red text")

	// 打印黄色的背景、紫色的文本
	color.New(color.BgYellow, color.FgMagenta).Println("This is a text with yellow background and magenta text color")

	// 自定义颜色样式
	customStyle := color.New(color.FgGreen, color.Bold, color.Underline)
	customStyle.Println("This is a custom style text")
}

在示例代码中,我们首先导入了github.com/fatih/color库。然后,我们使用color.Red打印了一个红色的文本。

接下来,我们使用color.New创建了一个新的颜色样式,并将其应用到Println方法中,以打印具有自定义背景和文本颜色的文本。

最后,我们创建了一个自定义的颜色样式customStyle,其中包含绿色、粗体和下划线。我们使用Println方法将其应用于一段文本,并打印出来。

集成 Logrus 自定义日志颜色【信息】

我们需要定义一个继承 logrus.TextFormatter 的结构体 CustomTextFormatter,并实现Format方法来自定义日志的输出格式。还需要将Logrus 实例的 Formatter 设置为自定义格式化器 CustomTextFormatter。而不是直接使用logrus.TextFormatter

CustomTextFormatter 结构体中,我们添加了ForceColors属性以及四个color.Color用于不同级别的日志消息。

同时在 CustomTextFormatterFormat 方法中根据日志级别选择设置对应的自定义颜色并打印日志消息。如果ForceColorstrue,则使用定义的颜色样式来打印日志;否则,调用父类的TextFormatter.Format方法进行默认的格式化操作。

PrintColored方法用于默认颜色的方式打印日志条目。它将日志级别添加到消息前面,并根据需要添加调用者信息。最后,通过调用fmt.Fprintln(color.Output, msg)将带颜色的消息打印到终端。

package main

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
	"strconv"
)

func main() {
    
    
	logger := logrus.New()
	logger.Formatter = &CustomTextFormatter{
    
    
		ForceColors:   true,
		ColorInfo:     color.New(color.FgBlue),
		ColorWarning:  color.New(color.FgYellow),
		ColorError:    color.New(color.FgRed),
		ColorCritical: color.New(color.BgRed, color.FgWhite),
	}

	logger.Info("This is an info message")     // 输出蓝色的信息日志
	logger.Warn("This is a warning message")   // 输出黄色的警告日志
	logger.Error("This is an error message")   // 输出红色的错误日志
	logger.Fatal("This is a critical message") // 输出带有红色背景和白色文本的严重日志

	logger.Panic("This is a critical message with panic") // 输出带有红色背景和白色文本的严重日志,并引发 panic
}

// 自定义格式化器,继承自 logrus.TextFormatter
type CustomTextFormatter struct {
    
    
	logrus.TextFormatter
	ForceColors   bool
	ColorInfo     *color.Color
	ColorWarning  *color.Color
	ColorError    *color.Color
	ColorCritical *color.Color
}

// 格式化方法,用于将日志条目格式化为字节数组
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
    
    
	if f.ForceColors {
    
    
		switch entry.Level {
    
    
		case logrus.InfoLevel:
			f.ColorInfo.Println(entry.Message) // 使用蓝色打印信息日志
		case logrus.WarnLevel:
			f.ColorWarning.Println(entry.Message) // 使用黄色打印警告日志
		case logrus.ErrorLevel:
			f.ColorError.Println(entry.Message) // 使用红色打印错误日志
		case logrus.FatalLevel, logrus.PanicLevel:
			f.ColorCritical.Println(entry.Message) // 使用带有红色背景和白色文本的样式打印严重日志
		default:
			f.PrintColored(entry)
		}
		return nil, nil
	} else {
    
    
		return f.TextFormatter.Format(entry)
	}
}

// 自定义方法,用于将日志条目以带颜色的方式打印出来
func (f *CustomTextFormatter) PrintColored(entry *logrus.Entry) {
    
    
	levelColor := color.New(color.FgCyan, color.Bold)             // 定义蓝色和粗体样式
	levelText := levelColor.Sprintf("%-6s", entry.Level.String()) // 格式化日志级别文本

	msg := levelText + " " + entry.Message
	if entry.HasCaller() {
    
    
		msg += " (" + entry.Caller.File + ":" + strconv.Itoa(entry.Caller.Line) + ")" // 添加调用者信息
	}

	fmt.Fprintln(color.Output, msg) // 使用有颜色的方式打印消息到终端
}

最终,我们实现了logger.Infologger.Warnlogger.Error等方法打印了不同级别的日志消息,并根据自定义的颜色进行输出。

**注意:**颜色的显示效果取决于你所使用的终端环境和配置。在某些情况下,可能需要配置终端来支持颜色输出。

集成 Logrus 自定义日志颜色【级别+时间戳+信息】

package main

import (
    "fmt"
    "github.com/fatih/color"
    "github.com/sirupsen/logrus"
    "strconv"
    "time"
)

func main() {
    
    
    logger := logrus.New()
    // 设置自定义格式化程序
    logger.Formatter = &CustomTextFormatter{
    
    
       ForceColors:   false,
       ColorInfo:     color.New(color.FgBlue),
       ColorWarning:  color.New(color.FgYellow),
       ColorError:    color.New(color.FgRed),
       ColorCritical: color.New(color.BgRed, color.FgWhite),
    }

    // 打印日志消息
    logger.Info("This is an info message")
    logger.Warn("This is a warning message")
    logger.Error("This is an error message")
    logger.Fatal("This is a critical message")

    logger.Panic("This is a critical message with panic")
}

type CustomTextFormatter struct {
    
    
    ForceColors   bool         // 强制使用颜色
    ColorInfo     *color.Color // Info级别日志颜色
    ColorWarning  *color.Color // Warn级别日志颜色
    ColorError    *color.Color // Error级别日志颜色
    ColorCritical *color.Color // Critical级别日志颜色
}

// Format 自定义Format方法
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
    
    
    if f.ForceColors {
    
    
       // 如果强制使用颜色,则根据日志级别打印带有颜色的输出
       switch entry.Level {
    
    
       case logrus.InfoLevel:
          f.ColorInfo.Println(formatMessageWithTimestamp(entry))
       case logrus.WarnLevel:
          f.ColorWarning.Println(formatMessageWithTimestamp(entry))
       case logrus.ErrorLevel:
          f.ColorError.Println(formatMessageWithTimestamp(entry))
       case logrus.FatalLevel, logrus.PanicLevel:
          f.ColorCritical.Println(formatMessageWithTimestamp(entry))
       default:
          f.PrintColored(entry)
       }
       return nil, nil
    } else {
    
    
       // 否则,返回默认格式化输出
       return f.formatDefault(entry)
    }
}

// 格式化默认输出的方法
func (f *CustomTextFormatter) formatDefault(entry *logrus.Entry) ([]byte, error) {
    
    
    timestamp := entry.Time.Format(time.DateTime)
    level := entry.Level.String()
    msg := entry.Message

    return []byte(fmt.Sprintf("[%s] %s %s\n", level, timestamp, msg)), nil
}

// PrintColored 打印带颜色的日志输出的方法
func (f *CustomTextFormatter) PrintColored(entry *logrus.Entry) {
    
    
    levelColor := color.New(color.FgCyan, color.Bold)
    levelText := levelColor.Sprintf("%-6s", entry.Level.String())

    msg := levelText + " " + formatMessageWithTimestamp(entry)
    if entry.HasCaller() {
    
    
       msg += " (" + entry.Caller.File + ":" + strconv.Itoa(entry.Caller.Line) + ")"
    }

    fmt.Fprintln(color.Output, msg)
}

// 格式化消息并添加时间戳
func formatMessageWithTimestamp(entry *logrus.Entry) string {
    
    
    timestamp := entry.Time.Format(time.DateTime)
    level := entry.Level.String()
    return "[" + level + "]" + timestamp + " " + entry.Message
}

猜你喜欢

转载自blog.csdn.net/qq_20185737/article/details/133560820