Skip to content

Commit

Permalink
Merge pull request #430 from ShotaKitazawa/issue/428
Browse files Browse the repository at this point in the history
use slog instead of logrus
  • Loading branch information
ShotaKitazawa authored Jan 21, 2024
2 parents f7e887f + d5ab3fc commit 08ea3df
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 31 deletions.
6 changes: 5 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/labstack/echo/v4 v4.11.4
github.com/markbates/goth v1.78.0
github.com/mattn/go-jsonpointer v0.0.1
github.com/sirupsen/logrus v1.9.3
github.com/samber/slog-echo v1.12.1
github.com/thanhpk/randstr v1.0.6
k8s.io/api v0.29.1
k8s.io/apimachinery v0.29.1
Expand Down Expand Up @@ -53,11 +53,15 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/samber/lo v1.38.1 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.opentelemetry.io/otel v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/oauth2 v0.12.0 // indirect
Expand Down
13 changes: 10 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,10 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/samber/slog-echo v1.12.1 h1:TgpA4luiqe2sa6SDsraM1hUcLAXF8ZofjXM0SzIJkJc=
github.com/samber/slog-echo v1.12.1/go.mod h1:/f78pHjVxGrIlHlS5fzWiW+BxkWltQ+SWKk8LKMjAMQ=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
Expand Down Expand Up @@ -270,6 +272,10 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opentelemetry.io/otel v1.19.0 h1:MuS/TNf4/j4IXsZuJegVzI1cwut7Qc00344rgH7p8bs=
go.opentelemetry.io/otel v1.19.0/go.mod h1:i0QyjOq3UPoTzff0PJB2N66fb4S0+rSbSB15/oyH9fY=
go.opentelemetry.io/otel/trace v1.19.0 h1:DFVQmlVbfVeOuBRrwdtaehRrWiL1JoVs9CPIQ1Dzxpg=
go.opentelemetry.io/otel/trace v1.19.0/go.mod h1:mfaSyvGyEJEI0nyV2I4qhNQnbBOUUmYZpYojqMnX2vo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand All @@ -288,6 +294,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand Down Expand Up @@ -390,7 +398,6 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
Expand Down
6 changes: 3 additions & 3 deletions server/controller/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package controller

import (
"fmt"
"log/slog"

"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"

"github.com/ShotaKitazawa/kube-portal/server/models/ports"
"github.com/ShotaKitazawa/kube-portal/server/view"
Expand All @@ -16,14 +16,14 @@ var (
)

type K8sController struct {
logger *logrus.Logger
logger *slog.Logger
k8sClient ports.Kubernetes
view view.Iface

jwtSecret string
}

func NewK8sController(l *logrus.Logger, k8sClient ports.Kubernetes, jwtSecret string, showUntaggedLinks bool) *K8sController {
func NewK8sController(l *slog.Logger, k8sClient ports.Kubernetes, jwtSecret string, showUntaggedLinks bool) *K8sController {
v := &view.JSON{ShowUntaggedLinks: showUntaggedLinks}
return &K8sController{l, k8sClient, v, jwtSecret}
}
Expand Down
6 changes: 3 additions & 3 deletions server/controller/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controller
import (
"context"
"fmt"
"log/slog"
"net/http"
"time"

Expand All @@ -11,7 +12,6 @@ import (
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/github"
"github.com/sirupsen/logrus"

"github.com/ShotaKitazawa/kube-portal/server/models/ports"
"github.com/ShotaKitazawa/kube-portal/server/utils"
Expand All @@ -28,14 +28,14 @@ func init() {
}

type OAuthController struct {
logger *logrus.Logger
logger *slog.Logger

jwtSecret string
expiredTime time.Duration
allowGitHubUserIDs []string
}

func NewOAuthController(l *logrus.Logger, githubClient ports.GitHub, githubKey, githubSecret, callbackUrl string, jwtSecret string, expiredTime time.Duration, allowGitHubUserName ...string) (*OAuthController, error) {
func NewOAuthController(l *slog.Logger, githubClient ports.GitHub, githubKey, githubSecret, callbackUrl string, jwtSecret string, expiredTime time.Duration, allowGitHubUserName ...string) (*OAuthController, error) {
// set OAuth Provider
goth.UseProviders(
github.New(githubKey, githubSecret, callbackUrl),
Expand Down
6 changes: 3 additions & 3 deletions server/infrastructure/github/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ package github

import (
"context"
"log/slog"
"strconv"

"github.com/ShotaKitazawa/kube-portal/server/models/ports"
"github.com/google/go-github/github"
"github.com/sirupsen/logrus"
)

type Client struct {
logger *logrus.Logger
logger *slog.Logger
}

var _ ports.GitHub = (*Client)(nil)

func NewGitHubClient(l *logrus.Logger) *Client {
func NewGitHubClient(l *slog.Logger) *Client {
return &Client{l}
}

Expand Down
35 changes: 24 additions & 11 deletions server/infrastructure/kubernetes/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/url"
"regexp"
"strconv"
"strings"

"github.com/elliotchance/orderedmap/v2"
"github.com/mattn/go-jsonpointer"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
Expand All @@ -35,14 +35,14 @@ func init() {
}

type Client struct {
log *slog.Logger
clientset kubernetes.Interface
dynamic dynamic.Interface
log *logrus.Logger
}

var _ ports.Kubernetes = (*Client)(nil)

func NewClient(l *logrus.Logger, kubeconfigPath string) (*Client, error) {
func NewClient(logger *slog.Logger, kubeconfigPath string) (*Client, error) {
kubeConfig, err := buildConfig(kubeconfigPath)
if err != nil {
return nil, err
Expand All @@ -55,7 +55,7 @@ func NewClient(l *logrus.Logger, kubeconfigPath string) (*Client, error) {
if err != nil {
return nil, err
}
return &Client{client, dynamic, l}, nil
return &Client{logger, client, dynamic}, nil
}

func buildConfig(kubeconfig string) (*rest.Config, error) {
Expand All @@ -82,7 +82,14 @@ func (c *Client) ListIngress(ctx context.Context) (models.IngressInfoList, error
var result models.IngressInfoList
for _, ing := range ings.Items {
m := orderedmap.NewOrderedMap[string, models.IngressInfo]()
logger := c.log.With(
slog.String("name", ing.Name),
slog.String("namespace", ing.Namespace),
)
for key, val := range ing.Annotations {
logger = logger.With(
slog.String("annotation", key),
)
// Skip if it's not related annotation
if !strings.HasPrefix(key, ingressAnnotationPrefix) {
continue
Expand All @@ -92,7 +99,7 @@ func (c *Client) ListIngress(ctx context.Context) (models.IngressInfoList, error
// Extract value from annotations
l := ingressAnnotationMatcher.FindStringSubmatch(key)
if len(l) != 4 {
c.log.Warn("TODO_1")
logger.Warn("skip: annotation didn't match the matcher")
continue
}
ruleIdx, _ := strconv.Atoi(l[1])
Expand Down Expand Up @@ -120,7 +127,7 @@ func (c *Client) ListIngress(ctx context.Context) (models.IngressInfoList, error
tmpIngressInfo.IsPrivate = true
}
default:
c.log.Warn("TODO")
logger.Warn("skip: annotation is not supported")
continue
}
// Fill Fqdn & Path if first time
Expand All @@ -137,10 +144,12 @@ func (c *Client) ListIngress(ctx context.Context) (models.IngressInfoList, error
rvRule, err := jsonpointer.Get(obj,
fmt.Sprintf("/rules/%d/host", ruleIdx))
if err != nil {
c.log.Warn("TODO_2")
return nil, err
logger.Warn(fmt.Sprintf(
"skip: Ingress.spec.rules[%d].host is empty", ruleIdx))
continue
} else if rule, ok := rvRule.(string); !ok {
c.log.Warn("TODO_2")
logger.Warn(fmt.Sprintf(
"skip: Ingress.spec.rules[%d].host is empty", ruleIdx))
continue
} else {
tmpIngressInfo.Hostname = rule
Expand All @@ -149,10 +158,14 @@ func (c *Client) ListIngress(ctx context.Context) (models.IngressInfoList, error
rvPath, err := jsonpointer.Get(obj,
fmt.Sprintf("/rules/%d/http/paths/%d/path", ruleIdx, pathIdx))
if err != nil {
c.log.Warn("TODO_3")
logger.Warn(fmt.Sprintf(
`Ingress.spec.rules[%d].http.paths[%d].path is empty: use "/" as path`,
ruleIdx, pathIdx))
tmpIngressInfo.Path = "/"
} else if path, ok := rvPath.(string); !ok {
c.log.Warn("TODO_4")
logger.Warn(fmt.Sprintf(
`Ingress.spec.rules[%d].http.paths[%d].path is empty: use "/" as path`,
ruleIdx, pathIdx))
tmpIngressInfo.Path = "/"
} else {
tmpIngressInfo.Path = path
Expand Down
3 changes: 3 additions & 0 deletions server/infrastructure/kubernetes/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package kubernetes

import (
"context"
"io"
"log/slog"
"testing"

networkingv1 "k8s.io/api/networking/v1"
Expand Down Expand Up @@ -74,6 +76,7 @@ func TestClient_ListIngressInfo(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Client{
log: slog.New(slog.NewJSONHandler(io.Discard, nil)),
clientset: tt.fields.clientset,
}
got, err := c.ListIngress(tt.args.ctx)
Expand Down
26 changes: 19 additions & 7 deletions server/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package server

import (
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"time"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
slogecho "github.com/samber/slog-echo"

"github.com/ShotaKitazawa/kube-portal/cmd/kube-portal/flag"
"github.com/ShotaKitazawa/kube-portal/server/controller"
Expand All @@ -20,22 +22,24 @@ import (
func Run(opts *flag.Opts) error {
// New Instances
e := echo.New()
l := logrus.New()
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
}))
// New Clients
k8sClient, err := kubernetes.NewClient(l, opts.KubeConfigPath)
k8sClient, err := kubernetes.NewClient(logger, opts.KubeConfigPath)
if err != nil {
panic(err)
}
githubClient := github.NewGitHubClient(l)
githubClient := github.NewGitHubClient(logger)
// New Controllers
k8sController := controller.NewK8sController(l,
k8sController := controller.NewK8sController(logger,
k8sClient, opts.JwtSecret, opts.ShowUntaggedLinks)
u, err := url.Parse(fmt.Sprintf("%s/auth/callback", opts.BaseUrl))
if err != nil {
panic(err)
}
oauthController, err := controller.NewOAuthController(
l, githubClient,
logger, githubClient,
opts.GitHubOAuthKey, opts.GitHubOAuthSecret, u.String(),
opts.JwtSecret, time.Duration(opts.ExpiredHour)*time.Hour,
utils.Split(opts.GitHubAllowUsers, ",")...,
Expand All @@ -46,7 +50,15 @@ func Run(opts *flag.Opts) error {

// Middleware
e.Use(middleware.Recover())
e.Use(middleware.Logger())
loggerForMiddleware := slog.New(slog.NewJSONHandler(os.Stderr,
&slog.HandlerOptions{
AddSource: false,
}))
e.Use(slogecho.NewWithConfig(loggerForMiddleware, slogecho.Config{
WithUserAgent: true,
WithRequestID: true,
WithRequestHeader: true,
}))

// Route
e.Static("/", "./client/out")
Expand Down

0 comments on commit 08ea3df

Please sign in to comment.