# README
Glogger is the logger for mia-platform go services.
It uses logrus as logging library, and implements a middleware to be used with http gorilla mux router and fiber.
This library follow the Mia Platform logging guidelines.
Install
This library require golang at version >= 1.13
go get -u github.com/mia-platform/glogger/v3
Example usage
Basic logger initialization.
The allowed log level are those parsed by logrus ParseLevel (e.g. panic, fatal, error, warn, warning, info, debug, trace).
// Logger setup
log, err := glogger.InitHelper(glogger.InitOptions{Level: "info"})
if err != nil {
msg := fmt.Sprintf("An error occurred while creating the logger: %v", err)
panic(msg)
}
Setup log middleware
Two middleware loggers are available in the middleware
package of this library. To use them you need to import it:
import "github.com/mia-platform/glogger/v3/middleware"
Gorilla Mux
Init log middleware for mux router. This log the incoming request
and request completed
following the mia-platform guidelines.
r := mux.NewRouter()
r.Use(middleware.RequestGorillaMuxMiddlewareLogger(log, nil))
and, to retrieve logger injected in request context:
func(w http.ResponseWriter, req *http.Request) {
loggerFn := glogger.Get(req.Context())
loggerFn.Info("log message")
}
Fiber
With fiber, you can setup the middleware in this way:
app := fiber.New()
app.Use(middleware.RequestFiberMiddlewareLogger())
And then retrieve it from the handler's context like this:
func(c *fiber.Ctx) {
loggerFn := glogger.Get(c.UserContext())
loggerFn.Info("log message")
}
with excluded path
You can restrict the path where the logger middleware take effect using the second paramenter in RequestGorillaMuxMiddlewareLogger
. For example, this could be useful to exclude incoming request
and request completed
logging in path router.
Logger function is injected anyway in request context.
r := mux.NewRouter()
r.Use(middleware.RequestGorillaMuxMiddlewareLogger(log, []string{"/-/"}))
How to log error message
To log error message using default field
_, err := myFn()
if err != nil {
glogger.Get(req.Context()).WithError(err).Error("error calling function")
}
How to log custom fields
To log error message using default field
glogger.Get(req.Context()).WithField("key", "some field").Info("error calling function")
glogger.Get(req.Context()).WithFields(&logrus.Fields{
"key": "some field",
"another-key": "something"
}).Info("log with custom fields")
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Versioning
We use SemVer for versioning. For the versions available, see the tags on this repository.
License
This project is licensed under the Apache License 2.0 - see the LICENSE.md file for details