Search code examples
gologrus

Is it possible to swap 'msg' for 'message' with logrus logging


So when using Logrus I need the logging output to have the message key instead of msg key, but when I use the code below I get both, but msg is empty, how can I configure logrus to use 'message' instead of 'msg'?

contextLogger.WithField("logger_name",topic).WithField("message",messageString).Info()

Here's the log output when leaving .Info() empty // .Info() logs to the msg key

"logger_name": "logger","message": "log message","msg": "","time": "2020-08-12T15:14:48Z"

What I would like is to be able to use .Info(message) and have

"logger_name": "logger","message": "log message","time": "2020-08-12T15:14:48Z"

Is it possible to change default logging keys for .Info() etc?


Solution

  • You can do so using the FieldMap field of JSonFormatter:

        // FieldMap allows users to customize the names of keys for default fields.
        // As an example:
        // formatter := &JSONFormatter{
        //      FieldMap: FieldMap{
        //       FieldKeyTime:  "@timestamp",
        //       FieldKeyLevel: "@level",
        //       FieldKeyMsg:   "@message",
        //       FieldKeyFunc:  "@caller",
        //    },
        // }
        FieldMap FieldMap
    

    This allows you to override the default field names, including msg.

    Here's a short example (see on playground):

    package main
    
    import (
        log "github.com/sirupsen/logrus"
    )
    
    func main() {
        log.SetFormatter(&log.JSONFormatter{
            FieldMap: log.FieldMap{
                log.FieldKeyMsg: "message",
            },
        })
    
        log.WithField("logger_name", "topic2").Info("this is my message")
    }
    

    Output:

    {"level":"info","logger_name":"topic2","message":"this is my message","time":"2009-11-10T23:00:00Z"}
    

    The same override is available on the TextFormatter.