Answer the question
In order to leave comments, you need to log in
Is it acceptable to use logrus in projects like this?
You can configure the logger in main
package main
import (
"github.com/delgus/learn-log/pkg"
"github.com/sirupsen/logrus"
)
func main() {
configurateLogger()
logrus.Println("Hello")
pkg.Work("lala")
}
func configurateLogger() {
logrus.StandardLogger().SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02T15:04:05.999"})
level, err := logrus.ParseLevel("debug")
if err != nil {
level = logrus.InfoLevel
logrus.WithError(err).
WithField("event", "start.parse_level_fail").
Info("set log level to \"info\" by default")
}
logrus.SetLevel(level)
}
package pkg
import "github.com/sirupsen/logrus"
func Work(s string) {
logrus.Info(`i work`)
logrus.Debugf(`string: %s`, s)
}
Answer the question
In order to leave comments, you need to log in
Again I will answer :-) (as well as the question on the link)
Yes, you can use it as written, logrus itself has a global logger by default.
What is the essence of passing a logger in parameters?
Well...
We get rid of the global variable.
The logger is passed to the function explicitly.
We can pass differently configured logger to the same function.
For a small application, it doesn't matter how it will be written, with global variables or not, but for a larger application, support will become more difficult.
UPD. This is an example if all application errors are logged in the same style, but I wonder if anyone had a project where several different loggers were required?
func main() {
logger := logrus.New()
sites := []string{
"example.com",
"google.com",
}
DoParse(sites, logger)
}
func DoParse(sites []string, logger logrus.FieldLogger) {
for _, site := range sites {
logger.Infof("Start parse site: %s", site)
siteLogger := initLoggerForSite(site)
parseSite(site, siteLogger)
}
}
No.
So it is not possible. Your function configurateLogger()
is useless. It only operates on an internal variable logger
. To make the variable noticeably more global, you need to declare it in a wider context, outside the function (and not inside the operator :=
). And in order for it to be visible in other packages, it must be named with a capital letter var Logger = configurateLogger()
and all this goodness must be imported into other packages.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question