Skip to content

Commit

Permalink
Replace logrus with slog (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
alessiodionisi authored Feb 28, 2024
1 parent 21ff513 commit 9454972
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 40 deletions.
20 changes: 10 additions & 10 deletions cmd/gangway/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
htmltemplate "html/template"
"io"
"log/slog"
"net/http"
"net/url"
"os"
Expand All @@ -31,7 +32,6 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/heptiolabs/gangway/internal/oidc"
"github.com/heptiolabs/gangway/templates"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api/v1"
)
Expand Down Expand Up @@ -69,14 +69,14 @@ func serveTemplate(tmplFile string, data interface{}, w http.ResponseWriter) {
templatePath := filepath.Join(cfg.CustomHTMLTemplatesDir, tmplFile)
templateData, err := os.ReadFile(templatePath)
if err != nil {
log.Errorf("Failed to find template asset: %s at path: %s", tmplFile, templatePath)
slog.Error("Failed to find template asset", "asset", tmplFile, "path", templatePath)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

tmpl, err = tmpl.Parse(string(templateData))
if err != nil {
log.Errorf("Failed to parse template: %v", err)
slog.Error("Failed to parse template", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Expand All @@ -85,7 +85,7 @@ func serveTemplate(tmplFile string, data interface{}, w http.ResponseWriter) {

tmpl, err = tmpl.ParseFS(templates.FS, tmplFile)
if err != nil {
log.Errorf("Failed to parse template: %v", err)
slog.Error("Failed to parse template", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Expand Down Expand Up @@ -171,7 +171,7 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {

session, err := gangwayUserSession.Session.Get(r, "gangway")
if err != nil {
log.Errorf("Got an error in login: %s", err)
slog.Error("Got an error in login", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -278,7 +278,7 @@ func kubeConfigHandler(w http.ResponseWriter, r *http.Request) {

d, err := yaml.Marshal(generateKubeConfig(info))
if err != nil {
log.Errorf("Error creating kubeconfig - %s", err.Error())
slog.Error("Error creating kubeconfig", "error", err.Error())
http.Error(w, "Error creating kubeconfig", http.StatusInternalServerError)
return
}
Expand All @@ -294,12 +294,12 @@ func generateInfo(w http.ResponseWriter, r *http.Request) *userInfo {
if err != nil {
// let us know that we couldn't open the file. This only cause missing output
// does not impact actual function of program
log.Errorf("Failed to open CA file. %s", err)
slog.Error("Failed to open CA file", "error", err)
}
defer file.Close()
caBytes, err := io.ReadAll(file)
if err != nil {
log.Warningf("Could not read CA file: %s", err)
slog.Warn("Could not read CA file", "error", err)
}

// load the session cookies
Expand Down Expand Up @@ -350,7 +350,7 @@ func generateInfo(w http.ResponseWriter, r *http.Request) *userInfo {
kubeCfgUser := strings.Join([]string{username, cfg.ClusterName}, "@")

if cfg.EmailClaim != "" {
log.Warn("using the Email Claim config setting is deprecated. Gangway uses `UsernameClaim@ClusterName`. This field will be removed in a future version.")
slog.Warn("Using the Email Claim config setting is deprecated. Gangway uses `UsernameClaim@ClusterName`. This field will be removed in a future version.")
}

issuerURL, ok := claims["iss"].(string)
Expand All @@ -360,7 +360,7 @@ func generateInfo(w http.ResponseWriter, r *http.Request) *userInfo {
}

if cfg.ClientSecret == "" {
log.Warn("Setting an empty Client Secret should only be done if you have no other option and is an inherent security risk.")
slog.Warn("Setting an empty Client Secret should only be done if you have no other option and is an inherent security risk.")
}

info := &userInfo{
Expand Down
31 changes: 24 additions & 7 deletions cmd/gangway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"crypto/tls"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
Expand All @@ -29,7 +30,6 @@ import (
"github.com/heptiolabs/gangway/internal/oidc"
"github.com/heptiolabs/gangway/internal/session"
"github.com/justinas/alice"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)

Expand All @@ -42,19 +42,30 @@ var transportConfig *config.TransportConfig
// wrapper function for http logging
func httpLogger(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer log.Printf("%s %s %s", r.Method, r.URL, r.RemoteAddr)
defer slog.Debug("HTTP log", "method", r.Method, "url", r.URL, "remote-addr", r.RemoteAddr)
fn(w, r)
}
}

func main() {
cfgFile := flag.String("config", "", "The config file to use.")
logLevel := flag.String("log-level", "info", "The log level to use. (debug, info, warn, error)")
flag.Parse()

var logLevelVar = new(slog.LevelVar)

h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevelVar})
slog.SetDefault(slog.New(h))

if err := logLevelVar.UnmarshalText([]byte(*logLevel)); err != nil {
slog.Error("Could not parse log level", "error", err)
os.Exit(1)
}

var err error
cfg, err = config.NewConfig(*cfgFile)
if err != nil {
log.Errorf("Could not parse config file: %s", err)
slog.Error("Could not parse config file", "error", err)
os.Exit(1)
}

Expand Down Expand Up @@ -115,14 +126,20 @@ func main() {

// start up the http server
go func() {
log.Infof("Gangway started! Listening on: %s", bindAddr)
slog.Info("Gangway started", "address", bindAddr)

// exit with FATAL logging why we could not start
// example: FATA[0000] listen tcp 0.0.0.0:8080: bind: address already in use
if cfg.ServeTLS {
log.Fatal(httpServer.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile))
if err := httpServer.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile); err != nil {
slog.Error("Could not start HTTPS server", "error", err)
os.Exit(1)
}
} else {
log.Fatal(httpServer.ListenAndServe())
if err := httpServer.ListenAndServe(); err != nil {
slog.Error("Could not start HTTP server", "error", err)
os.Exit(1)
}
}
}()

Expand All @@ -131,7 +148,7 @@ func main() {
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
<-signalChan

log.Println("Shutdown signal received, exiting.")
slog.Info("Shutdown signal received, exiting")
// close the HTTP server
httpServer.Shutdown(context.Background())
}
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ require (
github.com/gorilla/sessions v1.2.2
github.com/justinas/alice v1.2.0
github.com/kelseyhightower/envconfig v1.4.0
github.com/sirupsen/logrus v1.9.3
golang.org/x/crypto v0.20.0
golang.org/x/oauth2 v0.17.0
gopkg.in/yaml.v2 v2.4.0
Expand All @@ -24,7 +23,6 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.31.0 // indirect
k8s.io/apimachinery v0.29.2 // indirect
Expand Down
7 changes: 0 additions & 7 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
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.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
Expand All @@ -88,9 +85,6 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
Expand All @@ -117,7 +111,6 @@ gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/apimachinery v0.29.2 h1:EWGpfJ856oj11C52NRCHuU7rFDwxev48z+6DSlGNsV8=
Expand Down
7 changes: 4 additions & 3 deletions internal/config/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ package config
import (
"crypto/tls"
"crypto/x509"
"log"
"log/slog"
"net"
"net/http"
"os"
Expand All @@ -39,12 +39,13 @@ func NewTransportConfig(trustedCAPath string) *TransportConfig {
// Read in the cert file
certs, err := os.ReadFile(trustedCAPath)
if err != nil {
log.Fatalf("Failed to append %q to RootCAs: %v", trustedCAPath, err)
slog.Error("Failed to append CA to RootCAs", "ca", trustedCAPath, "error", err)
os.Exit(1)
}

// Append our cert to the system pool
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
log.Println("No certs appended, using system certs only")
slog.Info("No certs appended, using system certs only")
}
}

Expand Down
3 changes: 1 addition & 2 deletions internal/oidc/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package oidc
import (
"bytes"
"encoding/base64"
"log"
"testing"

"github.com/golang-jwt/jwt/v5"
Expand All @@ -26,7 +25,7 @@ func TestParseToken(t *testing.T) {
base64Decode := func(src string) []byte {
data, err := base64.RawURLEncoding.DecodeString(src)
if err != nil {
log.Fatal("error:", err)
t.Fatalf("Error decoding base64 string: %v", err)
}

return data
Expand Down
3 changes: 1 addition & 2 deletions internal/session/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"testing"

"github.com/gorilla/sessions"
log "github.com/sirupsen/logrus"
)

func TestGenerateSessionKeys(t *testing.T) {
Expand Down Expand Up @@ -53,7 +52,7 @@ func TestCleanupSession(t *testing.T) {
defer ts.Close()
_, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
t.Fatalf("Error getting from test server: %v", err)
}
if session.Options.MaxAge != -1 {
t.Errorf("Session was not reset. Have max age of %d. Should have -1", session.Options.MaxAge)
Expand Down
14 changes: 7 additions & 7 deletions internal/session/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@ package session

import (
"fmt"
"github.com/gorilla/sessions"
log "github.com/sirupsen/logrus"
"math"
"math/rand"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gorilla/sessions"
)

func TestJoinSectionCookies(t *testing.T) {
var originalValue string
var value string
cookies := buildRandomCookies(2, 3800, "test_%d")
buildRequestWithCookies(cookies, func(cookies []*http.Cookie, r *http.Request) {
buildRequestWithCookies(t, cookies, func(cookies []*http.Cookie, r *http.Request) {
for _, c := range cookies {
originalValue += c.Value
}
Expand All @@ -44,7 +44,7 @@ func TestJoinSectionCookiesSingle(t *testing.T) {
var originalValue string
var value string
cookies := buildRandomCookies(1, 2000, "test_%d")
buildRequestWithCookies(cookies, func(cookies []*http.Cookie, r *http.Request) {
buildRequestWithCookies(t, cookies, func(cookies []*http.Cookie, r *http.Request) {
for _, c := range cookies {
originalValue += c.Value
}
Expand Down Expand Up @@ -96,7 +96,7 @@ func TestSplitAndJoin(t *testing.T) {
sectionCookies := splitCookie(originalValue)
cookies := buildCookiesFromValues(sectionCookies, "test_%d")
var value string
buildRequestWithCookies(cookies, func(cookies []*http.Cookie, r *http.Request) {
buildRequestWithCookies(t, cookies, func(cookies []*http.Cookie, r *http.Request) {
value = joinSectionCookies(r, "test")
})
if value != originalValue {
Expand All @@ -108,7 +108,7 @@ func TestSplitAndJoin(t *testing.T) {

type handleReq func([]*http.Cookie, *http.Request)

func buildRequestWithCookies(cookies []*http.Cookie, fn handleReq) {
func buildRequestWithCookies(t *testing.T, cookies []*http.Cookie, fn handleReq) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, cookie := range cookies {
r.AddCookie(cookie)
Expand All @@ -118,7 +118,7 @@ func buildRequestWithCookies(cookies []*http.Cookie, fn handleReq) {
defer ts.Close()
_, err := http.Get(ts.URL)
if err != nil {
log.Fatal(err)
t.Fatalf("Error getting from test server: %v", err)
}
}

Expand Down

0 comments on commit 9454972

Please sign in to comment.