Skip to content

Instantly share code, notes, and snippets.

@mbrevoort
Last active October 24, 2022 13:10
Show Gist options
  • Save mbrevoort/404c4ef5bb36bb35bc69 to your computer and use it in GitHub Desktop.
Save mbrevoort/404c4ef5bb36bb35bc69 to your computer and use it in GitHub Desktop.
Adding caller function, filename and line number to logrus log entries
package utils
import (
"runtime"
"github.com/Sirupsen/logrus"
)
// DecorateRuntimeContext appends line, file and function context to the logger
func DecorateRuntimeContext(logger *logrus.Entry) *logrus.Entry {
if pc, file, line, ok := runtime.Caller(1); ok {
fName := runtime.FuncForPC(pc).Name()
return logger.WithField("file", file).WithField("line", line).WithField("func", fName)
} else {
return logger
}
}
@wilfreddenton
Copy link

@sathishvj the way I am using this is as follows

Log := DecorateRuntimeContext // so I don't have to type it out every time
Log(logrus.WithFields(logrus.Fields{
        "key": "value"
})).Info("message")

I believe this function must be called inline and not packed away into some utility function because of the way it gets the line number and filename.

@sherryCP
Copy link

we will have to call this decorator function everytime we want to print a line?

@talalashraf
Copy link

in every function

@huongtx498
Copy link

formatter := runtime.Formatter{ChildFormatter: &log.TextFormatter{
	FullTimestamp: true,
}}
formatter.Line = true
log.SetFormatter(&formatter)
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
log.WithFields(log.Fields{
	"file": "main.go",
}).Info("Server is running...")

Note: import ( runtime "github.com/banzaicloud/logrus-runtime-formatter"
log "github.com/sirupsen/logrus")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment