gologrus

Add custom field only to error logs in logrus


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??


Solution

  • 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
    }