Skip to content

Commit

Permalink
feat: logger rework (theupdateframework#58)
Browse files Browse the repository at this point in the history
* feat(log): add global default logger

Signed-off-by: Marvin Drees <[email protected]>

* feat(log): exchange logger in library code

Signed-off-by: Marvin Drees <[email protected]>

* feat(log): remove logrus from testutil

Signed-off-by: Marvin Drees <[email protected]>

* feat(log): replace logrus in example code

Signed-off-by: Marvin Drees <[email protected]>

* chore(log): run go mod tidy for new logger

Signed-off-by: Marvin Drees <[email protected]>

* test: add tests for logger set/get functions

Signed-off-by: Marvin Drees <[email protected]>

---------

Signed-off-by: Marvin Drees <[email protected]>
  • Loading branch information
MDr164 authored and rdimitrov committed Jan 25, 2024
1 parent f9a18ab commit 8df1341
Show file tree
Hide file tree
Showing 17 changed files with 240 additions and 134 deletions.
8 changes: 5 additions & 3 deletions examples/cli/tuf-client/cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ package cmd

import (
"fmt"
stdlog "log"
"os"
"path/filepath"

"github.com/go-logr/stdr"
"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/rdimitrov/go-tuf-metadata/metadata/config"
"github.com/rdimitrov/go-tuf-metadata/metadata/updater"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -54,9 +55,10 @@ func init() {
}

func GetCmd(target string) error {
// handle verbosity level
// set logger and debug verbosity level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "get_cmd", stdlog.LstdFlags)))
if Verbosity {
log.SetLevel(log.DebugLevel)
stdr.SetVerbosity(5)
}

// verify the client environment was initialized and fetch path names
Expand Down
8 changes: 5 additions & 3 deletions examples/cli/tuf-client/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ package cmd
import (
"fmt"
"io"
stdlog "log"
"net/http"
"net/url"
"os"
"path/filepath"

"github.com/go-logr/stdr"
"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/rdimitrov/go-tuf-metadata/metadata/trustedmetadata"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand All @@ -48,9 +49,10 @@ func init() {

func InitializeCmd() error {
copyTrusted := true
// handle verbosity level
// set logger and debug verbosity level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "ini_cmd", stdlog.LstdFlags)))
if Verbosity {
log.SetLevel(log.DebugLevel)
stdr.SetVerbosity(5)
}

// prepare the local environment
Expand Down
4 changes: 2 additions & 2 deletions examples/cli/tuf-client/cmd/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"path/filepath"
"strings"

log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -74,7 +73,8 @@ func askForConfirmation() bool {
var response string
_, err := fmt.Scanln(&response)
if err != nil {
log.Fatal(err)
fmt.Println(err)
os.Exit(1)
}
switch strings.ToLower(response) {
case "y", "yes":
Expand Down
10 changes: 7 additions & 3 deletions examples/cli/tuf/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ package cmd

import (
"fmt"
stdlog "log"
"os"

log "github.com/sirupsen/logrus"
"github.com/go-logr/stdr"
"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/spf13/cobra"
)

Expand All @@ -33,9 +36,10 @@ func init() {
}

func InitializeCmd() error {
// handle verbosity level
// set logger and debug verbosity level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "ini_cmd", stdlog.LstdFlags)))
if Verbosity {
log.SetLevel(log.DebugLevel)
stdr.SetVerbosity(5)
}

fmt.Println("Initialization successful")
Expand Down
25 changes: 16 additions & 9 deletions examples/client/client_example.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ package main
import (
"fmt"
"io"
stdlog "log"
"net/http"
"net/url"
"os"
"path/filepath"

log "github.com/sirupsen/logrus"
"github.com/go-logr/stdr"

"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/rdimitrov/go-tuf-metadata/metadata/config"
"github.com/rdimitrov/go-tuf-metadata/metadata/updater"
)
Expand All @@ -30,30 +32,33 @@ const (
metadataURL = "https://jku.github.io/tuf-demo/metadata"
targetsURL = "https://jku.github.io/tuf-demo/targets"
targetName = "file1.txt"
verbosity = log.InfoLevel
verbosity = 4
generateRandomFolder = false
)

func main() {
// set debug level
log.SetLevel(verbosity)
// set logger to stdout with info level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "client_example", stdlog.LstdFlags)))
stdr.SetVerbosity(verbosity)

log := metadata.GetLogger()

// initialize environment - temporary folders, etc.
metadataDir, err := InitEnvironment()
if err != nil {
log.Fatal("Failed to initialize environment: ", err)
log.Error(err, "Failed to initialize environment")
}

// initialize client with Trust-On-First-Use
err = InitTrustOnFirstUse(metadataDir)
if err != nil {
log.Fatal("Trust-On-First-Use failed: ", err)
log.Error(err, "Trust-On-First-Use failed")
}

// download the desired target
err = DownloadTarget(metadataDir, targetName)
if err != nil {
log.Fatal("Download failed: ", err)
log.Error(err, "Download failed")
}
}

Expand Down Expand Up @@ -128,6 +133,8 @@ func InitTrustOnFirstUse(metadataDir string) error {
// get the target information, verifies if the target is already cached, and in case it
// is not cached, downloads the target file.
func DownloadTarget(localMetadataDir, target string) error {
log := metadata.GetLogger()

rootBytes, err := os.ReadFile(filepath.Join(localMetadataDir, "root.json"))
if err != nil {
return err
Expand Down Expand Up @@ -166,7 +173,7 @@ func DownloadTarget(localMetadataDir, target string) error {
return fmt.Errorf("failed while finding a cached target: %w", err)
}
if path != "" {
log.Infof("Target %s is already present at - %s", target, path)
log.V(4).Info("Target is already present", "target", target, "path", path)
}

// target is not present locally, so let's try to download it
Expand All @@ -175,7 +182,7 @@ func DownloadTarget(localMetadataDir, target string) error {
return fmt.Errorf("failed to download target file %s - %w", target, err)
}

log.Infof("Successfully downloaded target %s at - %s", target, path)
log.V(4).Info("Successfully downloaded target", "target", target, "path", path)

return nil
}
17 changes: 11 additions & 6 deletions examples/multirepo/client/client_example.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ package main

import (
"fmt"
stdlog "log"
"os"
"path/filepath"
"strings"

log "github.com/sirupsen/logrus"
"github.com/go-logr/stdr"

"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/rdimitrov/go-tuf-metadata/metadata/config"
"github.com/rdimitrov/go-tuf-metadata/metadata/multirepo"
"github.com/rdimitrov/go-tuf-metadata/metadata/updater"
Expand All @@ -27,12 +29,13 @@ import (
const (
metadataURL = "https://raw.githubusercontent.com/rdimitrov/go-tuf-metadata/main/examples/multirepo/repository/metadata"
targetsURL = "https://raw.githubusercontent.com/rdimitrov/go-tuf-metadata/main/examples/multirepo/repository/targets"
verbosity = log.InfoLevel
verbosity = 4
)

func main() {
// set debug level
log.SetLevel(verbosity)
// set logger to stdout with info level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "multirepo_client_example", stdlog.LstdFlags)))
stdr.SetVerbosity(verbosity)

// Bootstrap TUF
fmt.Printf("Bootstrapping the initial TUF repo - fetching map.json file and necessary trusted root files\n\n")
Expand Down Expand Up @@ -72,6 +75,8 @@ func main() {

// BootstrapTUF returns the map file and the related trusted root metadata files
func BootstrapTUF() ([]byte, map[string][]byte, error) {
log := metadata.GetLogger()

trustedRoots := map[string][]byte{}
mapBytes := []byte{}
// get working directory
Expand Down Expand Up @@ -122,7 +127,7 @@ func BootstrapTUF() ([]byte, map[string][]byte, error) {
return nil, nil, fmt.Errorf("failed while finding a cached target: %w", err)
}
if path != "" {
log.Infof("Target %s is already present at - %s", name, path)
log.V(4).Info("Target is already present", "target", name, "path", path)
}

// target is not present locally, so let's try to download it
Expand All @@ -147,7 +152,7 @@ func BootstrapTUF() ([]byte, map[string][]byte, error) {
repositoryName := strings.Split(name, string(os.PathSeparator))
trustedRoots[repositoryName[0]] = bytes
}
log.Infof("Successfully downloaded target %s at - %s", name, path)
log.V(4).Info("Successfully downloaded target", "target", name, "path", path)
}

return mapBytes, trustedRoots, nil
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ module github.com/rdimitrov/go-tuf-metadata
go 1.20

require (
github.com/go-logr/logr v1.2.4
github.com/go-logr/stdr v1.2.2
github.com/secure-systems-lab/go-securesystemslib v0.7.0
github.com/sigstore/sigstore v1.7.2
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.12.0
Expand Down
12 changes: 5 additions & 7 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw=
github.com/facebookgo/limitgroup v0.0.0-20150612190941-6abd8d71ec01 h1:IeaD1VDVBPlx3viJT9Md8if8IxxJnO+x0JCGb054heg=
github.com/facebookgo/muster v0.0.0-20150708232844-fd3d7953fd52 h1:a4DFiKFJiDRGFD1qIcqGLX/WlUMD9dyLSLDt+9QZgt8=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
Expand Down Expand Up @@ -45,14 +49,10 @@ github.com/secure-systems-lab/go-securesystemslib v0.7.0 h1:OwvJ5jQf9LnIAS83waAj
github.com/secure-systems-lab/go-securesystemslib v0.7.0/go.mod h1:/2gYnlnHVQ6xeGtfIqFy7Do03K4cdCY0A/GlJLDKLHI=
github.com/sigstore/sigstore v1.7.2 h1:MY0wSOhKWa8SIWSCO9SzFnUl+b7jbthgXHJpuUg31Qs=
github.com/sigstore/sigstore v1.7.2/go.mod h1:2IPD5YXrXoznfnIoVsDF7ARC1Nha8xIdLpsC4kEQh5w=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/theupdateframework/go-tuf v0.5.2 h1:habfDzTmpbzBLIFGWa2ZpVhYvFBoK0C1onC3a4zuPRA=
Expand All @@ -67,7 +67,6 @@ golang.org/x/exp v0.0.0-20221208152030-732eee02a75a h1:4iLhBPcpqFmylhnkbY3W0ONLU
golang.org/x/exp v0.0.0-20221208152030-732eee02a75a/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0=
Expand All @@ -88,6 +87,5 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/square/go-jose.v2 v2.6.0 h1:NGk74WTnPKBNUhNzQX7PYcTLUjoq7mzKk2OKbvwk2iI=
gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
24 changes: 24 additions & 0 deletions metadata/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright 2023 VMware, Inc.
//
// This product is licensed to you under the BSD-2 license (the "License").
// You may not use this product except in compliance with the BSD-2 License.
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to
// the terms and conditions of the subcomponent's license, as noted in the
// LICENSE file.
//
// SPDX-License-Identifier: BSD-2-Clause

package metadata

import "github.com/go-logr/logr"

var log logr.Logger = logr.Discard()

func SetLogger(logger logr.Logger) {
log = logger
}

func GetLogger() logr.Logger {
return log
}
34 changes: 34 additions & 0 deletions metadata/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2023 VMware, Inc.
//
// This product is licensed to you under the BSD-2 license (the "License").
// You may not use this product except in compliance with the BSD-2 License.
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to
// the terms and conditions of the subcomponent's license, as noted in the
// LICENSE file.
//
// SPDX-License-Identifier: BSD-2-Clause

package metadata

import (
stdlog "log"
"os"
"testing"

"github.com/go-logr/stdr"
"github.com/stretchr/testify/assert"
)

func TestSetLogger(t *testing.T) {
// This function is just a simple setter, no need for testing table
testLogger := stdr.New(stdlog.New(os.Stdout, "test", stdlog.LstdFlags))
SetLogger(testLogger)
assert.Equal(t, testLogger, log, "setting package global logger was unsuccessful")
}

func TestGetLogger(t *testing.T) {
// This function is just a simple getter, no need for testing table
testLogger := GetLogger()
assert.Equal(t, log, testLogger, "function did not return current logger")
}
Loading

0 comments on commit 8df1341

Please sign in to comment.