Last active
October 24, 2022 13:10
-
-
Save mbrevoort/404c4ef5bb36bb35bc69 to your computer and use it in GitHub Desktop.
Adding caller function, filename and line number to logrus log entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
in every function