use logrus for gin's log output

This commit is contained in:
Christoph Haas 2021-01-13 17:27:01 +01:00
parent d978fd560d
commit ec752f8b08
3 changed files with 63 additions and 5 deletions

View File

@ -1,19 +1,71 @@
package main
import (
"io/ioutil"
"os"
"github.com/h44z/wg-portal/internal/server"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
)
func main() {
log.Infof("Starting WireGuard Portal Server...")
_ = setupLogger(logrus.StandardLogger())
logrus.Infof("Starting WireGuard Portal Server...")
service := server.Server{}
if err := service.Setup(); err != nil {
log.Fatalf("Setup failed: %v", err)
logrus.Fatalf("Setup failed: %v", err)
}
service.Run()
log.Infof("Stopped WireGuard Portal Server...")
logrus.Infof("Stopped WireGuard Portal Server...")
}
func setupLogger(logger *logrus.Logger) error {
// Check environment variables for logrus settings
level, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
level = "debug" // Default logrus level
}
useJSON, ok := os.LookupEnv("LOG_JSON")
if !ok {
useJSON = "false" // Default use human readable logging
}
useColor, ok := os.LookupEnv("LOG_COLOR")
if !ok {
useColor = "true"
}
switch level {
case "off":
logger.SetOutput(ioutil.Discard)
case "info":
logger.SetLevel(logrus.InfoLevel)
case "debug":
logger.SetLevel(logrus.DebugLevel)
case "trace":
logger.SetLevel(logrus.TraceLevel)
}
var formatter logrus.Formatter
if useJSON == "false" {
f := new(logrus.TextFormatter)
f.TimestampFormat = "2006-01-02 15:04:05"
f.FullTimestamp = true
if useColor == "true" {
f.ForceColors = true
}
formatter = f
} else {
f := new(logrus.JSONFormatter)
f.TimestampFormat = "2006-01-02 15:04:05"
}
logger.SetFormatter(formatter)
return nil
}

1
go.mod
View File

@ -14,6 +14,7 @@ require (
github.com/sirupsen/logrus v1.7.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
github.com/toorop/gin-logrus v0.0.0-20200831135515-d2ee50d38dae
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20200609130330-bd2cb7843e1b
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
gorm.io/driver/sqlite v1.1.3

View File

@ -4,6 +4,7 @@ import (
"encoding/gob"
"errors"
"html/template"
"io/ioutil"
"math/rand"
"net/url"
"os"
@ -16,6 +17,7 @@ import (
"github.com/h44z/wg-portal/internal/ldap"
log "github.com/sirupsen/logrus"
ginlogrus "github.com/toorop/gin-logrus"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
@ -127,7 +129,10 @@ func (s *Server) Setup() error {
}
// Setup http server
s.server = gin.Default()
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = ioutil.Discard
s.server = gin.New()
s.server.Use(ginlogrus.Logger(log.StandardLogger()), gin.Recovery())
s.server.SetFuncMap(template.FuncMap{
"formatBytes": common.ByteCountSI,
"urlEncode": url.QueryEscape,