将自定义字段仅添加到logrus中的错误日志中。

huangapple go评论82阅读模式
英文:

Add custom field only to error logs in logrus

问题

我正在使用logrus来进行golang的日志记录。我使用以下语句进行日志记录。

logger.Info("")
logger.Errorf("Error message")

我的要求是在Errorf语句中添加一个自定义字段(severity),并满足以下约束条件。
1)如果在日志语句中指定了该字段(例如:logrus.WithField("severity", "critical").Errorf("Error message")),则应按以下方式打印指定的值。

ERRO[0000] Error message            severity=critical

2)如果未指定该字段,则应打印默认值。例如,这个日志语句logger.Errorf("Error message")应该打印如下内容。

ERRO[0000] Error message            severity=normal

注意:这仅适用于Errorf语句,其他语句应按正常方式工作。

有人能给我提供一种实现这个要求的方法吗?

英文:

I'm using logrus for logging in golang. I use the following statements for logging.

logger.Info("")
logger.Errorf("Error message")

My requirement is to have a custom field (severity) only in Errorf statements with the following constraints.

  1. If it is specified in the log statement (Ex: logrus.WithField("severity", "critical").Errorf("Error message")) it should print the specified value as below.
ERRO[0000] Error message            severity=critical
  1. If it is not specified, it should print a default value. For Example this(logger.Errorf("Error message")) log statement should print the follows.
ERRO[0000] Error message            severity=normal

Note : This should happen only for Errorf statements, which means others should works as normal.

Can someone suggest me a way to achieve this??

答案1

得分: 2

编写自定义的Hook,用于检查条目是否设置了severity字段,如果没有,则插入默认值。将该钩子附加到默认的全局日志记录器或您自己的日志记录器。

您可以通过在Hook.Levels()的返回值中仅包含logrus.ErrorLevel级别来限制钩子仅在logrus.ErrorLevel级别的条目上触发:

type ErrorHook struct {
}

func (h *ErrorHook) Levels() []logrus.Level {
    // 仅在 ErrorLevel 上触发(.Error()、.Errorf() 等)
	return []logrus.Level{logrus.ErrorLevel}
}

func (h *ErrorHook) Fire(e *logrus.Entry) error {
    // e.Data 是附加到条目的所有字段的映射
	if _, ok := e.Data["severity"]; !ok {
		e.Data["severity"] = "normal"
	}
	return nil
}

func main() {
	logrus.AddHook(&ErrorHook{})

	logrus.WithFields(logrus.Fields{"animal": "walrus"}).Info("A walrus appears")
    // time="2009-11-10T23:00:00Z" level=info msg="A walrus appears" animal=walrus
	logrus.WithFields(logrus.Fields{"animal": "walrus"}).Error("A error walrus appears")
    // time="2009-11-10T23:00:00Z" level=error msg="A error walrus appears" animal=walrus severity=normal
	logrus.WithFields(logrus.Fields{"animal": "walrus", "severity": "high"}).Error("An overriden severity error walrus appears")
    // time="2009-11-10T23:00:00Z" level=error msg="An overriden severity error walrus appears" animal=walrus severity=high
}
英文:

Write custom Hook that will check if entry has severity field set and if not insert default value. Attach that hook to either default global or your own logger.

You can limit hook to fire only on entries on logrus.ErrorLevel by including only that level in return value of Hook.Levels():

type ErrorHook struct {
}

func (h *ErrorHook) Levels() []logrus.Level {
    // fire only on ErrorLevel (.Error(), .Errorf(), etc.)
	return []logrus.Level{logrus.ErrorLevel}
}

func (h *ErrorHook) Fire(e *logrus.Entry) error {
    // e.Data is a map with all fields attached to entry
	if _, ok := e.Data["severity"]; !ok {
		e.Data["severity"] = "normal"
	}
	return nil
}

func main() {
	logrus.AddHook(&ErrorHook{})

	logrus.WithFields(logrus.Fields{"animal": "walrus"}).Info("A walrus appears")
    // time="2009-11-10T23:00:00Z" level=info msg="A walrus appears" animal=walrus
	logrus.WithFields(logrus.Fields{"animal": "walrus"}).Error("A error walrus appears")
    // time="2009-11-10T23:00:00Z" level=error msg="A error walrus appears" animal=walrus severity=normal
	logrus.WithFields(logrus.Fields{"animal": "walrus", "severity": "high"}).Error("An overriden severity error walrus appears")
    // time="2009-11-10T23:00:00Z" level=error msg="An overriden severity error walrus appears" animal=walrus severity=high
}

huangapple
  • 本文由 发表于 2022年1月7日 14:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/70617528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定