Skip to content

Commit

Permalink
feat(logging)!: Switch from go-kit/log to log/slog (#66)
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Henderson <[email protected]>
  • Loading branch information
hairyhenderson authored May 31, 2024
1 parent 92a9b73 commit 55e6e1e
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 100 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ fmt.Printf("Private LAN IP: %s\n", info.PrivLanIP)

[The MIT License](http://opensource.org/licenses/MIT)

Copyright (c) 2020-2021 Dave Henderson
Copyright (c) 2020-2024 Dave Henderson
2 changes: 1 addition & 1 deletion admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestCMReboot(t *testing.T) {
srv := staticResponseServer(t, body)

d := testCableModem(srv)
ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

o, err := d.CMReboot(ctx)
assert.NoError(t, err)
Expand Down
54 changes: 28 additions & 26 deletions cmd/hitron/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,54 @@ package main
import (
"flag"
"fmt"
"log/slog"
"os"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
)

type Level struct {
lev level.Option
s string
}
type LevelValue slog.Level

var _ flag.Value = (*Level)(nil)
var _ flag.Getter = (*LevelValue)(nil)

// String implements flag.Value
func (l *Level) String() string {
return l.s
func (l LevelValue) String() string {
switch slog.Level(l) {
case slog.LevelDebug:
return "debug"
case slog.LevelInfo:
return "info"
case slog.LevelWarn:
return "warn"
case slog.LevelError:
return "error"
default:
return fmt.Sprintf("unknown(%d)", l)
}
}

// Set implements flag.Value
func (l *Level) Set(s string) error {
l.s = s

func (l *LevelValue) Set(s string) error {
switch s {
case "debug":
l.lev = level.AllowDebug()
*l = LevelValue(slog.LevelDebug)
case "info":
l.lev = level.AllowInfo()
*l = LevelValue(slog.LevelInfo)
case "warn":
l.lev = level.AllowWarn()
*l = LevelValue(slog.LevelWarn)
case "error":
l.lev = level.AllowError()
*l = LevelValue(slog.LevelError)
default:
return fmt.Errorf("unrecognized log level %q", s)
}

return nil
}

// NewLogger -
func NewLogger(l Level) log.Logger {
logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
func (l LevelValue) Get() any {
return slog.Level(l)
}

// add common labels (displayed in order)
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
logger = level.NewFilter(logger, l.lev)
logger = log.With(logger, "caller", log.DefaultCaller)
// initLogger -
func initLogger(l LevelValue) {
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.Level(l)})

return logger
slog.SetDefault(slog.New(handler))
}
16 changes: 2 additions & 14 deletions cmd/hitron/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,14 @@ import (
"os/signal"
"syscall"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
hitron "github.com/hairyhenderson/hitron_coda"
)

type debugLogAdapter struct {
log.Logger
}

func (l debugLogAdapter) Logf(format string, args ...interface{}) {
_ = l.Log("msg", fmt.Sprintf(format, args...))
}

type opts struct {
host string
username string
password string
logLevel Level
logLevel LevelValue
}

func flags(args []string, o *opts) ([]string, error) {
Expand Down Expand Up @@ -91,9 +81,7 @@ func run(args []string) error {
return err
}

logger := NewLogger(o.logLevel)
debugLogger := debugLogAdapter{level.Debug(logger)}
ctx = hitron.ContextWithDebugLogger(ctx, debugLogger)
initLogger(o.logLevel)

cm, err := hitron.New(o.host, o.username, o.password)
if err != nil {
Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
module github.com/hairyhenderson/hitron_coda

go 1.19
go 1.22.3

require (
github.com/go-kit/log v0.2.1
github.com/stretchr/testify v1.9.0
golang.org/x/text v0.15.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
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/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
Expand Down
47 changes: 10 additions & 37 deletions hitron.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/cookiejar"
"net/http/httputil"
Expand All @@ -28,18 +29,17 @@ type debugTransport struct {
}

func (t *debugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
debugLogger := debugLoggerFromContext(req.Context())
if debugLogger == nil {
if !slog.Default().Enabled(req.Context(), slog.LevelDebug) {
return t.rt.RoundTrip(req)
}

drq, _ := httputil.DumpRequest(req, true)
debugLogger.Logf("request: %s", drq)
slog.DebugContext(req.Context(), "dumping request", slog.String("request", string(drq)))

resp, err := t.rt.RoundTrip(req)
if err == nil {
drs, _ := httputil.DumpResponse(resp, true)
debugLogger.Logf("response: %s", drs)
slog.DebugContext(req.Context(), "dumping response", slog.String("response", string(drs)))
}

return resp, err
Expand All @@ -57,13 +57,18 @@ func New(host, username, password string) (*CableModem, error) {
return nil, err
}

tr := http.DefaultTransport
if slog.Default().Enabled(context.Background(), slog.LevelDebug) {
tr = &debugTransport{tr}
}

client := &http.Client{
Jar: jar,
// Ignore redirects
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
Transport: &debugTransport{http.DefaultTransport},
Transport: tr,
}

creds := credentials{username, password}
Expand Down Expand Up @@ -92,38 +97,6 @@ func (c *CableModem) url(s string) *url.URL {
return c.base.ResolveReference(p)
}

type debugLogger interface {
Logf(format string, args ...interface{})
}

type debugLoggerKey struct{}

// ContextWithDebugLogger - add a logger for debugging the client
func ContextWithDebugLogger(ctx context.Context,
l interface {
Logf(format string, args ...interface{})
},
) context.Context {
return context.WithValue(ctx, debugLoggerKey{}, l)
}

type debugLoggerFunc func(format string, args ...interface{})

func (f debugLoggerFunc) Logf(format string, args ...interface{}) {
f(format, args...)
}

func debugLoggerFromContext(ctx context.Context) debugLogger {
if l := ctx.Value(debugLoggerKey{}); l != nil {
dl, ok := l.(debugLogger)
if ok {
return dl
}
}

return debugLoggerFunc(func(_ string, _ ...interface{}) {})
}

func (c *CableModem) getJSON(ctx context.Context, path string, o interface{}) error {
return c.sendRequest(ctx, http.MethodGet, path, http.NoBody, o)
}
Expand Down
8 changes: 4 additions & 4 deletions misc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestDNS(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.DNS(ctx)
assert.NoError(t, err)
Expand All @@ -71,7 +71,7 @@ func TestDDNS(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.DDNS(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -103,7 +103,7 @@ func TestHosts(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.Hosts(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -143,7 +143,7 @@ func TestUsersCSRF(t *testing.T) {
srv := staticResponseServer(t, body)

d := testCableModem(srv)
ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.UsersCSRF(ctx)
assert.NoError(t, err)
Expand Down
20 changes: 10 additions & 10 deletions wifi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestWiFiAccessControl(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiAccessControl(ctx)
assert.NoError(t, err)
Expand All @@ -38,7 +38,7 @@ func TestWiFiAccessControlStatus(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiAccessControlStatus(ctx)
assert.NoError(t, err)
Expand All @@ -59,7 +59,7 @@ func TestWiFiGuestSSID(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiGuestSSID(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -94,7 +94,7 @@ func TestWiFiRadios(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiRadios(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -141,7 +141,7 @@ func TestWiFiRadioDetails(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiRadioDetails(ctx, 2)
assert.NoError(t, err)
Expand Down Expand Up @@ -192,7 +192,7 @@ func TestWiFiRadiosAdvanced(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiRadiosAdvanced(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -278,7 +278,7 @@ func TestWiFiRadiosSurvey(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiRadiosSurvey(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -328,7 +328,7 @@ func TestWiFiSSIDs(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiSSIDs(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -370,7 +370,7 @@ func TestWiFiWPS(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiWPS(ctx)
assert.NoError(t, err)
Expand Down Expand Up @@ -400,7 +400,7 @@ func TestWiFiClient(t *testing.T) {
srv := staticResponseServer(t, body)
d := testCableModem(srv)

ctx := ContextWithDebugLogger(context.Background(), t)
ctx := context.Background()

p, err := d.WiFiClient(ctx)
assert.NoError(t, err)
Expand Down

0 comments on commit 55e6e1e

Please sign in to comment.