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 Nov 30, 2023
1 parent 5ae1ce4 commit 1312227
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 27 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
6 changes: 3 additions & 3 deletions exporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"text/template"
Expand All @@ -30,8 +30,8 @@ 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)
log.Fatal(http.ListenAndServe(listenAddress, router))
slog.Info("Starting exporter", "listenAddress", listenAddress)
slog.Info("Server stopped", "reason", http.ListenAndServe(listenAddress, router))
}

type targetHandler func(*triax.Client, http.ResponseWriter, *http.Request, httprouter.Params)
Expand Down
31 changes: 27 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ 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"
"github.com/digineo/triax-eoc-exporter/exporter"
)

// DefaultConfigPath points to the default config file location.
Expand Down Expand Up @@ -44,15 +44,38 @@ func main() {
kingpin.HelpFlag.Short('h')
kingpin.Parse()

initLogger(*verbose)

cfg, err := exporter.LoadConfig(*configFile)
if err != nil {
log.Fatal(err.Error())
}

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

func initLogger(verbose bool) {
opts := slog.HandlerOptions{
Level: slog.LevelInfo,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Remove time from the output
if a.Key == slog.TimeKey {
return slog.Attr{}
}

return a
},
}

if verbose {
opts.Level = slog.LevelDebug
}

logger := slog.New(slog.NewTextHandler(os.Stdout, &opts))
slog.SetDefault(logger)

}

func printVersion() {
info, ok := debug.ReadBuildInfo()
if !ok {
Expand Down
27 changes: 9 additions & 18 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 @@ -23,14 +22,9 @@ type Client struct {
password string
}

var (
// Verbose increases verbosity.
Verbose bool

HTTPClient = http.Client{
Timeout: time.Second * 30,
}
)
var HTTPClient = http.Client{
Timeout: time.Second * 30,
}

func init() {
HTTPClient.Jar, _ = cookiejar.New(nil) // error is always nil
Expand Down Expand Up @@ -123,9 +117,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.Info("HTTP Request", "method", method, "url", url)

var body io.Reader
if request != nil {
Expand Down Expand Up @@ -153,7 +145,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,19 +155,18 @@ 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))
}
if err != nil {
return fmt.Errorf("decoding response failed: %w", err)
}

slog.Debug("response received", "json", string(jsonData))
}

return nil
Expand Down

0 comments on commit 1312227

Please sign in to comment.