RocketMQ client modify the default log configuration [golang version]

Front description

go by defaultlogrus,但是提供了接口,可以自定义日志实现,官网说明如下:

Set Logger

Go Client define the Logger interface for log output, user can specify implementation of private. in default, client use logrus.

rlog.SetLogger(Logger)

Applicable scene

Custom log format, log output directory (used in scenarios such as collection, monitoring, statistical analysis, etc.)

Example

Custom log implementation

type myLogger struct {
	flag string
}

func (l *myLogger) Info(msg string, fields map[string]interface{}) {
	if msg == "" && len(fields) == 0 {
		return
	}
	log.Println(l.flag, "[info]", msg)
}

func (l *myLogger) Warning(msg string, fields map[string]interface{}) {
	if msg == "" && len(fields) == 0 {
		return
	}
	log.Println(l.flag, "[warn]", msg)
}

func (l *myLogger) Error(msg string, fields map[string]interface{}) {
	if msg == "" && len(fields) == 0 {
		return
	}
	log.Println(l.flag, "[error]", msg)
}

func (l *myLogger) Fatal(msg string, fields map[string]interface{}) {
	if msg == "" && len(fields) == 0 {
		return
	}
	log.Fatal(l.flag, "[fatal]", msg)
}

Set log implementation at startup

func main() {
	// 设置日志,默认使用logrus
	rlog.SetLogger(&myLogger{flag: "xuxd"})
    // 其它逻辑
    ...
}

The results of the operation are as follows:

Set log level

The go client prints info-level logs by default. I printed debug in the picture above because I set the log level to debug and only set the environment variable: ROCKETMQ_GO_LOG_LEVEL=debug

The example of goland I used is as follows:

Log source file

Source file name: log.go

type Logger interface {
	Debug(msg string, fields map[string]interface{})
	Info(msg string, fields map[string]interface{})
	Warning(msg string, fields map[string]interface{})
	Error(msg string, fields map[string]interface{})
	Fatal(msg string, fields map[string]interface{})
}

func init() {
	r := &defaultLogger{
		logger: logrus.New(),
	}
	level := os.Getenv("ROCKETMQ_GO_LOG_LEVEL")
	switch strings.ToLower(level) {
	case "debug":
		r.logger.SetLevel(logrus.DebugLevel)
	case "warn":
		r.logger.SetLevel(logrus.WarnLevel)
	case "error":
		r.logger.SetLevel(logrus.ErrorLevel)
	default:
		r.logger.SetLevel(logrus.InfoLevel)
	}
	rLog = r
}

 

Guess you like

Origin blog.csdn.net/x763795151/article/details/114704947