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"
}
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.
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.