mirror of
https://github.com/hamburghammer/gsave.git
synced 2025-03-15 02:25:55 +01:00
Implement logrus for logging
Fix wrong error handling if host was not found getting the stats for it. Add configuration flags to configure the logging.
This commit is contained in:
parent
3dfb18f67d
commit
7f817e166f
6 changed files with 64 additions and 21 deletions
|
@ -6,7 +6,7 @@ In the near future [gmon](https://github.com/hamburghammer/gmon) should use it t
|
|||
- [ ] Configure CI/CD pipeline
|
||||
- [ ] HTTP testing
|
||||
- [ ] Auth Middleware with Basic Auth
|
||||
- [ ] Flag configurable
|
||||
- [ ] Logging
|
||||
- [x] Flag configurable
|
||||
- [x] Logging
|
||||
- [ ] SQLite DB implementation
|
||||
- [ ] Env Variable configurable
|
|
@ -1,6 +1,19 @@
|
|||
package controller
|
||||
|
||||
import "github.com/gorilla/mux"
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
logPackage = log.WithField("Package", "controller")
|
||||
logRequestError = logPackage.WithField("RequestStatus", "Error")
|
||||
logBadRequest = logRequestError.WithField("StatusCode", http.StatusBadRequest)
|
||||
logNotFound = logRequestError.WithField("StatusCode", http.StatusNotFound)
|
||||
logInternalServerError = logRequestError.WithField("StatusCode", http.StatusInternalServerError)
|
||||
)
|
||||
|
||||
// Router is an interface that should be implemented by any controller
|
||||
// to give some information and to register the routes.
|
||||
|
|
|
@ -4,7 +4,6 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
|
@ -46,6 +45,7 @@ func (hr *HostsRouter) getHosts(w http.ResponseWriter, r *http.Request) {
|
|||
pagination, err := hr.getSkipAndLimit(r)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
logBadRequest.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -53,9 +53,11 @@ func (hr *HostsRouter) getHosts(w http.ResponseWriter, r *http.Request) {
|
|||
if err != nil {
|
||||
if errors.Is(err, db.ErrHostsNotFound) || errors.Is(err, db.ErrAllEntriesSkipped) {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
logNotFound.Error(err)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
logInternalServerError.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -65,15 +67,12 @@ func (hr *HostsRouter) getHosts(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
func (hr *HostsRouter) getHost(w http.ResponseWriter, r *http.Request) {
|
||||
hostname := mux.Vars(r)["hostname"]
|
||||
if hostname == "" {
|
||||
http.Error(w, fmt.Sprintf("Missing hostname: '%s' is not a valid hostname\n", hostname), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
host, err := hr.db.GetHost(hostname)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrHostNotFound) {
|
||||
http.Error(w, fmt.Sprintf("No host with the name '%s' found\n", hostname), http.StatusNotFound)
|
||||
logNotFound.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
@ -88,16 +87,19 @@ func (hr *HostsRouter) getStats(w http.ResponseWriter, r *http.Request) {
|
|||
pagination, err := hr.getSkipAndLimit(r)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
logBadRequest.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := hr.db.GetStatsByHostname(hostname, pagination)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrHostsNotFound) || errors.Is(err, db.ErrAllEntriesSkipped) {
|
||||
if errors.Is(err, db.ErrHostNotFound) || errors.Is(err, db.ErrAllEntriesSkipped) {
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
logNotFound.Error(err)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
logInternalServerError.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -112,14 +114,15 @@ func (hr *HostsRouter) postStats(w http.ResponseWriter, r *http.Request) {
|
|||
err := json.NewDecoder(r.Body).Decode(&stats)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
log.Println(err)
|
||||
logBadRequest.Error(err)
|
||||
return
|
||||
}
|
||||
log.Printf("Received stat: %+v", stats)
|
||||
logPackage.Debugf("Received stat: %+v", stats)
|
||||
|
||||
err = hr.db.InsertStats(hostname, stats)
|
||||
if err != nil {
|
||||
http.Error(w, "Something with the DB went wrong.", http.StatusInternalServerError)
|
||||
logInternalServerError.Error(err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
|
|
1
go.mod
1
go.mod
|
@ -4,5 +4,6 @@ go 1.15
|
|||
|
||||
require (
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/stretchr/testify v1.6.1
|
||||
)
|
||||
|
|
6
go.sum
6
go.sum
|
@ -1,12 +1,18 @@
|
|||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
|
|
40
main.go
40
main.go
|
@ -5,7 +5,6 @@ import (
|
|||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
@ -15,17 +14,38 @@ import (
|
|||
"github.com/gorilla/mux"
|
||||
"github.com/hamburghammer/gsave/controller"
|
||||
"github.com/hamburghammer/gsave/db"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var servePort int
|
||||
var (
|
||||
servePort int
|
||||
logPackage = log.WithField("Package", "main")
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.IntVar(&servePort, "port", 8080, "The port for the HTTP server.")
|
||||
verbose := flag.Bool("verbose", false, "Enable debug logging output.")
|
||||
quiet := flag.Bool("quiet", false, "Disable loging output only prints errors.")
|
||||
jsonLogging := flag.Bool("json", false, "Set the logging format to json.")
|
||||
flag.Parse()
|
||||
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
FullTimestamp: true,
|
||||
})
|
||||
|
||||
if *verbose {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
}
|
||||
if *quiet {
|
||||
log.SetLevel(log.ErrorLevel)
|
||||
}
|
||||
if *jsonLogging {
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.Println("Initializing the DB...")
|
||||
logPackage.Info("Initializing the DB...")
|
||||
stats := []db.Stats{
|
||||
{Hostname: "foo", CPU: 0},
|
||||
{Hostname: "foo", CPU: 1},
|
||||
|
@ -33,16 +53,16 @@ func main() {
|
|||
}
|
||||
hostDB, err := initDB(stats)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
logPackage.Fatal(err)
|
||||
}
|
||||
|
||||
log.Println("Initializing the routes...")
|
||||
logPackage.Info("Initializing the routes...")
|
||||
controllers := []controller.Router{
|
||||
controller.NewHostsRouter(hostDB),
|
||||
}
|
||||
router := initRouter(hostDB, controllers)
|
||||
|
||||
log.Println("Starting the HTTP server...")
|
||||
logPackage.Info("Starting the HTTP server...")
|
||||
server := &http.Server{
|
||||
Handler: router,
|
||||
Addr: fmt.Sprintf(":%d", servePort),
|
||||
|
@ -81,13 +101,13 @@ func initRouter(hostDB db.HostDB, controllers []controller.Router) *mux.Router {
|
|||
|
||||
func startHTTPServer(server *http.Server, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
log.Printf("The HTTP server is running: http://localhost:%d/hosts\n", servePort)
|
||||
logPackage.Infof("The HTTP server is running: http://localhost:%d/hosts\n", servePort)
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
log.Println("Shutting down the server...")
|
||||
logPackage.Info("Shutting down the server...")
|
||||
return
|
||||
}
|
||||
log.Fatalf("An unexpected error happend while running the HTTP server: %v\n", err)
|
||||
logPackage.Fatalf("An unexpected error happend while running the HTTP server: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -102,6 +122,6 @@ func listenToStopHTTPServer(server *http.Server, wg *sync.WaitGroup) {
|
|||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
log.Printf("An error happened on the shutdown of the server: %v", err)
|
||||
logPackage.Errorf("An error happened on the shutdown of the server: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue