Logrus: log.withFields returns empty field values when used globally

Created on 13 Sep 2018  路  7Comments  路  Source: sirupsen/logrus

I am trying to log certain global fields in all my logs. These fields are declared globally and set at different times in my program.

However the output values are always empty for these fields. I am new to golang. Please guide, sorry if I have missed something basic here...

import log "github.com/sirupsen/logrus"

var {
logger                      *log.Entry,
globalSid                  int
} 

func init() {
    log.SetOutput(os.Stdout)

    // Only log the warning severity or above.
    log.SetLevel(log.DebugLevel)

    filenameHook := filename.NewHook()
    filenameHook.Field = "src" // Customize source field name
    log.AddHook(filenameHook)

    Formatter := new(log.TextFormatter)
    Formatter.TimestampFormat = "02-01-2006 15:04:05"
    Formatter.FullTimestamp = true

    log.SetFormatter(Formatter)

    logger = log.WithFields(log.Fields{
        "Sid":   globalSid,
    })
}

func main() {

globalSid =100

logger.Debug("test") 
//DEBU[13-09-2018 15:42:42] test  Sid=0 src="dir/app.go:1186"
}
question

Most helpful comment

@kickbox I've added in #842 an example which contains the gist on how to procede. Let me know if that helps.

All 7 comments

This is an expected behaviour, you are creating the entry while the value of your global variable is set to 0. Any further change to the global variable won't be reflected in your traces.

Thank you for the response. Is there a way to achieve this? I would like to print current values of a fixed set of variables in all my logs.

you can register a hook which can then add dyncamilly the current value of global variable as field of the entry.

Thanks. I am not sure how to do that yet. Will try to figure this out...

@kickbox I've added in #842 an example which contains the gist on how to procede. Let me know if that helps.

@kickbox does that help ? Can we close this issue ?

@dgsb thank you so much for this, I have not tested it yet. But I think this will be useful and will incorporate when I refactor.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

demizer picture demizer  路  4Comments

kaushikchaubal picture kaushikchaubal  路  5Comments

penhauer-xiao picture penhauer-xiao  路  4Comments

vagruchi picture vagruchi  路  5Comments

UnAfraid picture UnAfraid  路  5Comments