Skip to content

Commit

Permalink
Switch to log/slog package
Browse files Browse the repository at this point in the history
  • Loading branch information
corny committed Sep 26, 2023
1 parent 55b5580 commit 9eb6cd8
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 22 deletions.
4 changes: 2 additions & 2 deletions exporter/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package exporter
import (
"context"
"fmt"
"log"
"log/slog"
"strconv"

"github.com/digineo/triax-eoc-exporter/triax"
Expand Down Expand Up @@ -72,7 +72,7 @@ func (t *triaxCollector) Collect(ch chan<- prometheus.Metric) {
ch <- prometheus.MustNewConstMetric(ctrlUp, prometheus.GaugeValue, boolToFloat(err == nil))

if err != nil {
log.Println("fetching failed:", err)
slog.Error("fetching failed", "error", err)
}
}

Expand Down
3 changes: 2 additions & 1 deletion exporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"text/template"
Expand All @@ -30,7 +31,7 @@ func (cfg *Config) Start(listenAddress, version string) {
router.GET("/controllers/:target/api/*path", cfg.targetMiddleware(cfg.apiHandler))
router.PUT("/controllers/:target/nodes/:mac", cfg.targetMiddleware(cfg.updateNodeHandler))

log.Printf("Starting exporter on http://%s/", listenAddress)
slog.Info("Starting exporter", "address", fmt.Sprintf("http://%s/", listenAddress))
log.Fatal(http.ListenAndServe(listenAddress, router))
}

Expand Down
28 changes: 22 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package main
import (
"fmt"
"log"
"log/slog"
"os"
"runtime/debug"

"github.com/digineo/triax-eoc-exporter/exporter"
"github.com/digineo/triax-eoc-exporter/triax"

kingpin "github.com/alecthomas/kingpin/v2"
)
Expand Down Expand Up @@ -36,10 +37,10 @@ func main() {
"Path to config.toml that contains all the targets.",
).Default(DefaultConfigPath).String()

verbose := kingpin.Flag(
"verbose",
"Increase verbosity",
).Bool()
logLevel := kingpin.Flag(
"log.level",
"Set log level (debug/info/warn/error)",
).Default("info").String()

kingpin.HelpFlag.Short('h')
kingpin.Parse()
Expand All @@ -49,10 +50,25 @@ func main() {
log.Fatal(err.Error())
}

triax.Verbose = *verbose
setLogger(*logLevel)
cfg.Start(*listenAddress, version)
}

func setLogger(logLevel string) {

levelVar := slog.LevelVar{}

if err := levelVar.UnmarshalText([]byte(logLevel)); err != nil {
log.Panicf("Invalid log level %s: %v", logLevel, err)
}

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: levelVar.Level(),
}))

slog.SetDefault(logger)
}

func printVersion() {
info, ok := debug.ReadBuildInfo()
if !ok {
Expand Down
20 changes: 7 additions & 13 deletions triax/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"log/slog"
"net/http"
"net/http/cookiejar"
"net/url"
Expand All @@ -24,9 +23,6 @@ type Client struct {
}

var (
// Verbose increases verbosity.
Verbose bool

HTTPClient = http.Client{
Timeout: time.Second * 30,
}
Expand Down Expand Up @@ -123,9 +119,7 @@ retry:
func (c *Client) apiRequestRaw(ctx context.Context, method, path string, request, response interface{}) error {
url := fmt.Sprintf("%s://%s/api/%s", c.endpoint.Scheme, c.endpoint.Host, strings.TrimPrefix(path, "/"))

if Verbose {
log.Printf("%s %s", method, url)
}
slog.Debug("Fetching", "method", method, "url", url)

var body io.Reader
if request != nil {
Expand Down Expand Up @@ -153,7 +147,7 @@ func (c *Client) apiRequestRaw(ctx context.Context, method, path string, request
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
data, _ := ioutil.ReadAll(res.Body)
data, _ := io.ReadAll(res.Body)

return &ErrUnexpectedStatus{
Method: method,
Expand All @@ -163,16 +157,16 @@ func (c *Client) apiRequestRaw(ctx context.Context, method, path string, request
}
}

jsonData, err := ioutil.ReadAll(res.Body)
jsonData, err := io.ReadAll(res.Body)
if err != nil {
return err
}

if response != nil {
err = json.Unmarshal(jsonData, &response)
if Verbose || err != nil {
log.Println(string(jsonData))
}

slog.Debug("Response", "body", string(jsonData))

if err != nil {
return fmt.Errorf("decoding response failed: %w", err)
}
Expand Down

0 comments on commit 9eb6cd8

Please sign in to comment.