Skip to content

Commit

Permalink
replace log15 with slog from std library
Browse files Browse the repository at this point in the history
  • Loading branch information
ulrichSchreiner committed Jan 2, 2024
1 parent 7369742 commit 7e7bcfe
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 30 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
vendor
bin
.vscode
.devcontainer
59 changes: 39 additions & 20 deletions cmd/directipserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import (
"context"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"

"github.com/inconshreveable/log15"
"github.com/lmittmann/tint"
"github.com/protegear/sbd"
"github.com/protegear/sbd/mux"
yaml "gopkg.in/yaml.v2"
Expand All @@ -29,7 +32,7 @@ var (
revision string
builddate string
distribution mux.Distributer
log log15.Logger
log *slog.Logger
)

func main() {
Expand All @@ -45,7 +48,7 @@ func main() {

setLogOutput(*logformat, *loglevel)

log = log15.New("stage", *stage)
log = slog.With("stage", *stage)

listen := defaultListen
if len(flag.Args()) > 0 {
Expand All @@ -57,19 +60,19 @@ func main() {
if *config != "" {
cfg, err := os.Open(*config)
if err != nil {
log.Crit("cannot open config file", "config", *config, "error", err)
log.Error("cannot open config file", "config", *config, "error", err)
os.Exit(1)
}

var targets mux.Targets
err = yaml.NewDecoder(cfg).Decode(&targets)
if err != nil {
log.Crit("cannot unmarshal data", "error", err)
log.Error("cannot unmarshal data", "error", err)
os.Exit(1)
}
err = distribution.WithTargets(targets)
if err != nil {
log.Crit("cannot use config", "error", err)
log.Error("cannot use config", "error", err)
os.Exit(1)
}
log.Info("change configuration", "targets", targets)
Expand All @@ -94,7 +97,7 @@ func runHealth(health string) {
}))
}

func watchServices(ctx context.Context, log log15.Logger, client *rest.Config, s mux.Distributer) {
func watchServices(ctx context.Context, log *slog.Logger, client *rest.Config, s mux.Distributer) {
clientset, err := kubernetes.NewForConfig(client)
if err != nil {
log.Error("cannot create clientset for services", "error", err)
Expand Down Expand Up @@ -176,7 +179,7 @@ func targetFromService(s *v1.Service) *mux.Target {
}
ip := s.Spec.ClusterIP
if ip != "" {
log15.Info("found target", "imei", t, "path", path, "port", port, "ip", ip)
slog.Info("found target", "imei", t, "path", path, "port", port, "ip", ip)
bk := mux.Target{
ID: string(s.ObjectMeta.UID),
Backend: fmt.Sprintf("http://%s:%s%s", ip, port, path),
Expand All @@ -189,18 +192,34 @@ func targetFromService(s *v1.Service) *mux.Target {
}

func setLogOutput(format, loglevel string) {
h := log15.CallerFileHandler(log15.StreamHandler(os.Stdout, log15.JsonFormat()))
switch format {
case logFMT:
h = log15.CallerFileHandler(log15.StreamHandler(os.Stdout, log15.LogfmtFormat()))
case logTERM:
h = log15.CallerFileHandler(log15.StreamHandler(os.Stdout, log15.TerminalFormat()))
lvl := slog.LevelDebug
switch strings.ToLower(loglevel) {
case "debug":
lvl = slog.LevelDebug
case "info":
lvl = slog.LevelInfo
case "warn":
lvl = slog.LevelWarn
case "error", "crit":
lvl = slog.LevelError
}
lvl, e := log15.LvlFromString(loglevel)
if e != nil {
lvl = log15.LvlInfo
log15.Error("cannot parse level from parameter", "level", loglevel, "error", e)

if format == "logfmt" || format == "term" {
w := os.Stdout
slog.SetDefault(slog.New(
tint.NewHandler(w, &tint.Options{
AddSource: true,
Level: lvl,
TimeFormat: time.DateTime,
}),
))
} else {
w := os.Stdout
slog.SetDefault(slog.New(
slog.NewJSONHandler(w, &slog.HandlerOptions{
AddSource: true,
Level: lvl,
}),
))
}
target := log15.LvlFilterHandler(lvl, h)
log15.Root().SetHandler(target)
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require (
github.com/google/gofuzz v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lmittmann/tint v1.0.3 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
Expand Down Expand Up @@ -55,4 +56,4 @@ require (
k8s.io/client-go v0.26.1
)

go 1.20
go 1.21
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lmittmann/tint v1.0.3 h1:W5PHeA2D8bBJVvabNfQD/XW9HPLZK1XoPZH0cq8NouQ=
github.com/lmittmann/tint v1.0.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
Expand Down
10 changes: 5 additions & 5 deletions mux/distributor.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log/slog"
"net/http"
"regexp"

"github.com/inconshreveable/log15"
"github.com/protegear/sbd"
)

Expand Down Expand Up @@ -46,7 +46,7 @@ type Distributer interface {
}

type distributer struct {
log15.Logger
*slog.Logger
targets []Target
sbdChannel chan *sbdMessage
configChannel chan Targets
Expand All @@ -58,7 +58,7 @@ type sbdMessage struct {
}

// New creates a new Distributor with the given number of workers
func New(numworkers int, log log15.Logger) Distributer {
func New(numworkers int, log *slog.Logger) Distributer {
sc := make(chan *sbdMessage)
cc := make(chan Targets)
s := &distributer{
Expand Down Expand Up @@ -157,7 +157,7 @@ func (f *distributer) handle(m *sbdMessage) {
return
}
defer rsp.Body.Close()
content, _ := ioutil.ReadAll(rsp.Body)
content, _ := io.ReadAll(rsp.Body)
if rsp.StatusCode/100 == 2 {
f.Info("data transmitted", "target", t.Backend, "status", rsp.Status, "content", string(content))
} else {
Expand Down
8 changes: 4 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"encoding/binary"
"encoding/json"
"fmt"
"log/slog"
"net"
"time"

"github.com/inconshreveable/log15"
proxyproto "github.com/pires/go-proxyproto"
)

Expand All @@ -33,7 +33,7 @@ func (f HandlerFunc) Handle(data *InformationBucket) error {

// Logger is a middleware function which wraps a handler with logging
// capabilities.
func Logger(log log15.Logger, next Handler) Handler {
func Logger(log *slog.Logger, next Handler) Handler {
return HandlerFunc(func(data *InformationBucket) error {
js, err := json.Marshal(data)
if err != nil {
Expand All @@ -58,7 +58,7 @@ func createResult(status byte) *result {
// short burst data packet to the given handler. If the handler returns a
// non-nil error, the service will send a negative response, otherwise the
// responsestatus will be ok.
func NewService(log log15.Logger, address string, h Handler, proxyprotocol bool) error {
func NewService(log *slog.Logger, address string, h Handler, proxyprotocol bool) error {
l, err := net.Listen("tcp", address)
if err != nil {
return fmt.Errorf("cannot open listening address %q: %v", address, err)
Expand All @@ -71,7 +71,7 @@ func NewService(log log15.Logger, address string, h Handler, proxyprotocol bool)
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Crit("cannot accept", "error", err)
log.Error("cannot accept", "error", err)
// let it crash! it's up to the caller of the prog to restart it
panic(err)
}
Expand Down

0 comments on commit 7e7bcfe

Please sign in to comment.