Skip to content

Instantly share code, notes, and snippets.

@mbrevoort
Last active October 24, 2022 13:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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
}
}
@sathishvj
Copy link

Trying to figure this out. How do I pass this decorator to an instance of *logrus.Logger? And every time a log statement like logger.Printf() is run, will it take this data?

Do you have any code that uses this decorator?

@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