diff --git a/cmd/internal/serverutil/serverutil.go b/cmd/internal/serverutil/serverutil.go index 6708dc9..b540cdf 100644 --- a/cmd/internal/serverutil/serverutil.go +++ b/cmd/internal/serverutil/serverutil.go @@ -36,7 +36,9 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/reflection" - "github.com/trustbloc/vct/internal/pkg/log" + "github.com/trustbloc/logutil-go/pkg/log" + + logfields "github.com/trustbloc/vct/internal/pkg/log" ) var logger = log.New("internal/serverutil") @@ -153,7 +155,7 @@ func (m *Main) Run(ctx context.Context) error { // nolint: funlen }() } - logger.Info("RPC server starting", log.WithServiceEndpoint(m.RPCEndpoint)) + logger.Info("RPC server starting", logfields.WithServiceEndpoint(m.RPCEndpoint)) lis, err := net.Listen("tcp", m.RPCEndpoint) if err != nil { @@ -239,11 +241,11 @@ func AnnounceSelf(ctx context.Context, client *clientv3.Client, etcdService, end fullEndpoint := fmt.Sprintf("%s/%s", etcdService, endpoint) em.AddEndpoint(ctx, fullEndpoint, endpoints.Endpoint{Addr: endpoint}) // nolint: errcheck, gosec - logger.Info("Announcing our presence", log.WithServiceEndpoint(etcdService)) + logger.Info("Announcing our presence", logfields.WithServiceEndpoint(etcdService)) return func() { // Use a background context because the original context may have been cancelled. - logger.Info("Removing our presence", log.WithServiceEndpoint(etcdService)) + logger.Info("Removing our presence", logfields.WithServiceEndpoint(etcdService)) ctx := context.Background() em.DeleteEndpoint(ctx, fullEndpoint) // nolint: errcheck, gosec diff --git a/cmd/log_server/main.go b/cmd/log_server/main.go index 3b8485b..e39f6ff 100644 --- a/cmd/log_server/main.go +++ b/cmd/log_server/main.go @@ -20,10 +20,10 @@ import ( "github.com/google/trillian/quota" "github.com/google/trillian/storage" + "github.com/trustbloc/logutil-go/pkg/log" "github.com/trustbloc/vct/cmd/internal/serverutil" "github.com/trustbloc/vct/cmd/log_server/startcmd" - "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/pkg/storage/memory" "github.com/trustbloc/vct/pkg/storage/postgres" ) diff --git a/cmd/log_signer/main.go b/cmd/log_signer/main.go index 4d81ea2..e1ea035 100644 --- a/cmd/log_signer/main.go +++ b/cmd/log_signer/main.go @@ -20,9 +20,9 @@ import ( "github.com/google/trillian/log" "github.com/google/trillian/quota" "github.com/google/trillian/storage" + logs "github.com/trustbloc/logutil-go/pkg/log" "github.com/trustbloc/vct/cmd/log_signer/startcmd" - logs "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/pkg/storage/memory" "github.com/trustbloc/vct/pkg/storage/postgres" ) diff --git a/cmd/vct/main.go b/cmd/vct/main.go index c3d7be8..b25f335 100644 --- a/cmd/vct/main.go +++ b/cmd/vct/main.go @@ -23,9 +23,9 @@ package main import ( "github.com/spf13/cobra" + "github.com/trustbloc/logutil-go/pkg/log" "github.com/trustbloc/vct/cmd/vct/startcmd" - "github.com/trustbloc/vct/internal/pkg/log" ) var logger = log.New("vct") diff --git a/cmd/vct/startcmd/start.go b/cmd/vct/startcmd/start.go index e8c4eba..ba973a0 100644 --- a/cmd/vct/startcmd/start.go +++ b/cmd/vct/startcmd/start.go @@ -55,6 +55,7 @@ import ( "github.com/rs/cors" "github.com/spf13/cobra" awssvc "github.com/trustbloc/kms/pkg/aws" + "github.com/trustbloc/logutil-go/pkg/log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/durationpb" @@ -64,7 +65,7 @@ import ( logsignerstart "github.com/trustbloc/vct/cmd/log_signer/startcmd" "github.com/trustbloc/vct/internal/pkg/cmdutil" "github.com/trustbloc/vct/internal/pkg/ldcontext" - "github.com/trustbloc/vct/internal/pkg/log" + logfields "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/internal/pkg/tlsutil" "github.com/trustbloc/vct/pkg/controller/command" "github.com/trustbloc/vct/pkg/controller/rest" @@ -928,7 +929,7 @@ func createTreeAndInit(conn *grpc.ClientConn, cfg storage.Store, alias string, t return err // nolint: wrapcheck }, backoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), timeout), func(err error, duration time.Duration) { logger.Warn("Create tree failed, will sleep a while before trying again", - log.WithBackoff(duration), log.WithError(err)) + logfields.WithBackoff(duration), log.WithError(err)) }) if err != nil { @@ -1079,7 +1080,7 @@ func createStoreProvider(dbURL, prefix string, timeout uint64) (storeProvider, e timeout, ), func(retryErr error, t time.Duration) { logger.Warn("Failed to connect to storage, will sleep a while before trying again", - log.WithBackoff(t), log.WithError(retryErr)) + logfields.WithBackoff(t), log.WithError(retryErr)) }) } diff --git a/go.mod b/go.mod index 138d784..2a04744 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/cucumber/godog v0.9.0 github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.2 - github.com/google/go-cmp v0.5.7 + github.com/google/go-cmp v0.5.9 github.com/google/trillian v1.3.14-0.20210520152752-ceda464a95a3 github.com/google/uuid v1.3.0 github.com/gorilla/mux v1.8.0 @@ -31,8 +31,9 @@ require ( github.com/spf13/cobra v1.3.0 github.com/stretchr/testify v1.8.1 github.com/trustbloc/kms v0.1.9-0.20221024131747-f895f91207f1 + github.com/trustbloc/logutil-go v1.0.0-rc1 go.etcd.io/etcd/client/v3 v3.5.0 - go.uber.org/zap v1.17.0 + go.uber.org/zap v1.23.0 google.golang.org/grpc v1.44.0 google.golang.org/protobuf v1.28.1 ) @@ -131,6 +132,8 @@ require ( go.etcd.io/etcd/client/pkg/v3 v3.5.1 // indirect go.mongodb.org/mongo-driver v1.8.0 // indirect go.opencensus.io v0.23.0 // indirect + go.opentelemetry.io/otel v1.12.0 // indirect + go.opentelemetry.io/otel/trace v1.12.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.6.0 // indirect golang.org/x/crypto v0.1.0 // indirect diff --git a/go.sum b/go.sum index e1be0f3..76d943b 100644 --- a/go.sum +++ b/go.sum @@ -155,6 +155,7 @@ github.com/aws/aws-sdk-go v1.43.9 h1:k1S/29Bp2QD5ZopnGzIn0Sp63yyt3WH1JRE2OOU3Aig github.com/aws/aws-sdk-go v1.43.9/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod h1:q/89r3U2H7sSsE2t6Kca0lfwTK8JdoNGS/yzM/4iH5I= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -334,6 +335,8 @@ github.com/go-kivik/kiviktest/v3 v3.0.3/go.mod h1:sqsz3M2sJxTxAUdOj+2SU21y4phcpY github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -414,8 +417,9 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-github/v28 v28.1.1/go.mod h1:bsqJWQX05omyWVmc00nEUql9mhQyv38lDZ8kPZcQVoM= github.com/google/go-licenses v0.0.0-20210329231322-ce1d9163b77d/go.mod h1:+TYOmkVoJOpwnS0wfdsJCV9CoD5nJYsHoFk/0CrTK4M= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= @@ -1011,6 +1015,8 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1 github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= github.com/trustbloc/kms v0.1.9-0.20221024131747-f895f91207f1 h1:u617zM5QPsAawgQq8n797jj1PTBIp+7fHbmKjd/FeQM= github.com/trustbloc/kms v0.1.9-0.20221024131747-f895f91207f1/go.mod h1:Vv+mv35QeUo5f+Llm/gsp6x4FgLkLH9dTp4dGK0+aQU= +github.com/trustbloc/logutil-go v1.0.0-rc1 h1:rRJbvgQfrlUfyej+mY0nuQJymGqjRW4oZEwKi544F4c= +github.com/trustbloc/logutil-go v1.0.0-rc1/go.mod h1:JlxT0oZfNKgIlSNtgc001WEeDMxlnAvOM43gNm8DQVc= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= @@ -1095,6 +1101,11 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.22.6/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/otel v1.12.0 h1:IgfC7kqQrRccIKuB7Cl+SRUmsKbEwSGPr0Eu+/ht1SQ= +go.opentelemetry.io/otel v1.12.0/go.mod h1:geaoz0L0r1BEOR81k7/n9W4TCXYCJ7bPO7K374jQHG0= +go.opentelemetry.io/otel/sdk v1.12.0 h1:8npliVYV7qc0t1FKdpU08eMnOjgPFMnriPhn0HH4q3o= +go.opentelemetry.io/otel/trace v1.12.0 h1:p28in++7Kd0r2d8gSt931O57fdjUyWxkVbESuILAeUc= +go.opentelemetry.io/otel/trace v1.12.0/go.mod h1:pHlgBynn6s25qJ2szD+Bv+iwKJttjHSI3lUAyf0GNuQ= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -1103,6 +1114,7 @@ go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= @@ -1113,8 +1125,9 @@ go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= -go.uber.org/zap v1.17.0 h1:MTjgFu6ZLKvY6Pvaqk97GlxNBuMpV4Hy/3P6tRGlI2U= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= +go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY= +go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= gocloud.dev v0.19.0/go.mod h1:SmKwiR8YwIMMJvQBKLsC3fHNyMwXLw3PMDO+VVteJMI= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= diff --git a/internal/pkg/log/common.go b/internal/pkg/log/common.go deleted file mode 100644 index eee9237..0000000 --- a/internal/pkg/log/common.go +++ /dev/null @@ -1,14 +0,0 @@ -/* -Copyright SecureKey Technologies Inc. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package log - -import "go.uber.org/zap" - -// WriteResponseBodyError outputs a 'write response body' error log to the given logger. -func WriteResponseBodyError(log *Log, err error) { - log.WithOptions(zap.AddCallerSkip(1)).Error("Error writing response body", WithError(err)) -} diff --git a/internal/pkg/log/common_test.go b/internal/pkg/log/common_test.go deleted file mode 100644 index 5140fbd..0000000 --- a/internal/pkg/log/common_test.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright SecureKey Technologies Inc. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package log - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestCommonLogs(t *testing.T) { - const module = "test_module" - - t.Run("WriteResponseBodyError", func(t *testing.T) { - stdErr := newMockWriter() - - logger := New(module, - WithStdErr(stdErr), - WithFields(WithServiceName("myservice")), - ) - - WriteResponseBodyError(logger, errors.New("response body error")) - - require.Contains(t, stdErr.Buffer.String(), `Error writing response body`) - require.Contains(t, stdErr.Buffer.String(), `"service": "myservice"`) - require.Contains(t, stdErr.Buffer.String(), `"error": "response body error"`) - require.Contains(t, stdErr.Buffer.String(), "log/common_test.go") - }) -} diff --git a/internal/pkg/log/fields.go b/internal/pkg/log/fields.go index 51922a7..9b068ab 100644 --- a/internal/pkg/log/fields.go +++ b/internal/pkg/log/fields.go @@ -17,7 +17,6 @@ import ( const ( FieldServiceName = "service" FieldSize = "size" - FieldAddress = "address" FieldBackoff = "backoff" FieldServiceEndpoint = "serviceEndpoint" FieldTreeID = "treeID" @@ -30,11 +29,6 @@ const ( FieldPublicKey = "publicKey" ) -// WithError sets the error field. -func WithError(err error) zap.Field { - return zap.Error(err) -} - // WithServiceName sets the service field. func WithServiceName(value string) zap.Field { return zap.String(FieldServiceName, value) @@ -45,11 +39,6 @@ func WithSize(value int) zap.Field { return zap.Int(FieldSize, value) } -// WithAddress sets the address field. -func WithAddress(value string) zap.Field { - return zap.String(FieldAddress, value) -} - // WithBackoff sets the backoff field. func WithBackoff(value time.Duration) zap.Field { return zap.Duration(FieldBackoff, value) diff --git a/internal/pkg/log/fields_test.go b/internal/pkg/log/fields_test.go index f9f3ed1..74921ad 100644 --- a/internal/pkg/log/fields_test.go +++ b/internal/pkg/log/fields_test.go @@ -7,13 +7,14 @@ SPDX-License-Identifier: Apache-2.0 package log import ( + "bytes" "encoding/json" - "errors" "net/url" "testing" "time" "github.com/stretchr/testify/require" + "github.com/trustbloc/logutil-go/pkg/log" ) func TestStandardFields(t *testing.T) { @@ -21,49 +22,16 @@ func TestStandardFields(t *testing.T) { u1 := parseURL(t, "https://example1.com") - t.Run("console error", func(t *testing.T) { - stdErr := newMockWriter() - - logger := New(module, - WithStdErr(stdErr), - WithFields(WithServiceName("myservice")), - ) - - logger.Error("Sample error", WithError(errors.New("some error"))) - - require.Contains(t, stdErr.Buffer.String(), `Sample error {"service": "myservice", "error": "some error"}`) - }) - - t.Run("json error", func(t *testing.T) { - stdErr := newMockWriter() - - logger := New(module, - WithStdErr(stdErr), WithEncoding(JSON), - WithFields(WithServiceName("myservice")), - ) - - logger.Error("Sample error", WithError(errors.New("some error"))) - - l := unmarshalLogData(t, stdErr.Bytes()) - - require.Equal(t, "myservice", l.Service) - require.Equal(t, "test_module", l.Logger) - require.Equal(t, "Sample error", l.Msg) - require.Contains(t, l.Caller, "log/fields_test.go") - require.Equal(t, "some error", l.Error) - require.Equal(t, "error", l.Level) - }) - t.Run("json fields", func(t *testing.T) { leaf := &mockObject{Field1: "leaf1", Field2: 32123} pubKey := &mockObject{Field1: "key1", Field2: 32432} stdOut := newMockWriter() - logger := New(module, WithStdOut(stdOut), WithEncoding(JSON)) + logger := log.New(module, log.WithStdOut(stdOut), log.WithEncoding(log.JSON)) logger.Info("Some message", - WithServiceName("service1"), WithSize(1234), WithAddress(u1.String()), + WithServiceName("service1"), WithSize(1234), WithBackoff(time.Minute), WithServiceEndpoint(u1.String()), WithTreeID(1234), WithLeaf(leaf), WithStore("store1"), WithCommand("doit"), WithVerifiableCredential([]byte(`"id":"vc1"`)), WithSignature([]byte("my signature")), @@ -76,7 +44,6 @@ func TestStandardFields(t *testing.T) { require.Equal(t, `Some message`, l.Msg) require.Equal(t, `service1`, l.Service) require.Equal(t, 1234, l.Size) - require.Equal(t, u1.String(), l.Address) require.Equal(t, "1m0s", l.Backoff) require.Equal(t, u1.String(), l.ServiceEndpoint) require.Equal(t, 1234, l.TreeID) @@ -105,7 +72,6 @@ type logData struct { Service string `json:"service"` Size int `json:"size"` - Address string `json:"address"` Backoff string `json:"backoff"` ServiceEndpoint string `json:"serviceEndpoint"` TreeID int `json:"treeID"` @@ -136,3 +102,15 @@ func parseURL(t *testing.T, raw string) *url.URL { return u } + +type mockWriter struct { + *bytes.Buffer +} + +func (m *mockWriter) Sync() error { + return nil +} + +func newMockWriter() *mockWriter { + return &mockWriter{Buffer: bytes.NewBuffer(nil)} +} diff --git a/internal/pkg/log/logger.go b/internal/pkg/log/logger.go deleted file mode 100644 index d03589f..0000000 --- a/internal/pkg/log/logger.go +++ /dev/null @@ -1,394 +0,0 @@ -/* -Copyright SecureKey Technologies Inc. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package log - -import ( - "errors" - "fmt" - "os" - "strings" - "sync" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -const ( - timestampKey = "time" - levelKey = "level" - moduleKey = "logger" - callerKey = "caller" - messageKey = "msg" - stacktraceKey = "stacktrace" -) - -// DefaultEncoding sets the default logger encoding. -// It may be overridden at build time using the -ldflags option. -var DefaultEncoding = Console //nolint:gochecknoglobals - -// Level defines a log level for logging messages. -type Level int - -// String returns string representation of given log level. -func (l Level) String() string { - switch l { - case DEBUG: - return "DEBUG" - case INFO: - return "INFO" - case WARNING: - return "WARN" - case ERROR: - return "ERROR" - case PANIC: - return "PANIC" - case FATAL: - return "FATAL" - default: - return fmt.Sprintf("Level(%d)", l) - } -} - -// ParseLevel returns the level from the given string. -func ParseLevel(level string) (Level, error) { - switch level { - case "DEBUG", "debug": - return DEBUG, nil - case "INFO", "info": - return INFO, nil - case "WARN", "warn", "WARNING", "warning": - return WARNING, nil - case "ERROR", "error": - return ERROR, nil - case "PANIC", "panic": - return PANIC, nil - case "FATAL", "fatal": - return FATAL, nil - default: - return ERROR, errors.New("logger: invalid log level") - } -} - -// Log levels. -const ( - DEBUG = Level(zapcore.DebugLevel) - INFO = Level(zapcore.InfoLevel) - WARNING = Level(zapcore.WarnLevel) - ERROR = Level(zapcore.ErrorLevel) - PANIC = Level(zapcore.PanicLevel) - FATAL = Level(zapcore.FatalLevel) - - minLogLevel = DEBUG - defaultLevel = INFO -) - -var levels = newModuleLevels() //nolint:gochecknoglobals - -type options struct { - encoding Encoding - stdOut zapcore.WriteSyncer - stdErr zapcore.WriteSyncer - fields []zap.Field -} - -// Encoding defines the log encoding. -type Encoding = string - -// Log encodings. -const ( - Console Encoding = "console" - JSON Encoding = "json" -) - -const defaultModuleName = "" - -// Option is a logger option. -type Option func(o *options) - -// WithStdOut sets the output for logs of type DEBUG, INFO, and WARN. -func WithStdOut(stdOut zapcore.WriteSyncer) Option { - return func(o *options) { - o.stdOut = stdOut - } -} - -// WithStdErr sets the output for logs of type ERROR, PANIC, and FATAL. -func WithStdErr(stdErr zapcore.WriteSyncer) Option { - return func(o *options) { - o.stdErr = stdErr - } -} - -// WithFields sets the fields that will be output with every log. -func WithFields(fields ...zap.Field) Option { - return func(o *options) { - o.fields = fields - } -} - -// WithEncoding sets the output encoding (console or json). -func WithEncoding(encoding Encoding) Option { - return func(o *options) { - o.encoding = encoding - } -} - -// Log uses the Zap Logger to log messages in a structured way. -type Log struct { - *zap.Logger - module string -} - -// New creates a structured Logger implementation based on given module name. -func New(module string, opts ...Option) *Log { - options := getOptions(opts) - - return &Log{ - Logger: newZap(module, options.encoding, options.stdOut, options.stdErr).With(options.fields...), - module: module, - } -} - -// IsEnabled returns true if given log level is enabled. -func (l *Log) IsEnabled(level Level) bool { - return levels.isEnabled(l.module, level) -} - -// SetLevel sets the log level for given module and level. -func SetLevel(module string, level Level) { - levels.Set(module, level) -} - -// SetDefaultLevel sets the default log level. -func SetDefaultLevel(level Level) { - levels.SetDefault(level) -} - -// GetLevel returns the log level for the given module. -func GetLevel(module string) Level { - return levels.Get(module) -} - -// SetSpec sets the log levels for individual modules as well as the default log level. -// The format of the spec is as follows: -// -// module1=level1:module2=level2:module3=level3:defaultLevel -// -// Valid log levels are: critical, error, warning, info, debug -// -// Example: -// -// module1=error:module2=debug:module3=warning:info -func SetSpec(spec string) error { - logLevelByModule := strings.Split(spec, ":") - - defaultLogLevel := minLogLevel - 1 - - var moduleLevelPairs []moduleLevelPair - - for _, logLevelByModulePart := range logLevelByModule { - if strings.Contains(logLevelByModulePart, "=") { - moduleAndLevelPair := strings.Split(logLevelByModulePart, "=") - - logLevel, err := ParseLevel(moduleAndLevelPair[1]) - if err != nil { - return err - } - - moduleLevelPairs = append(moduleLevelPairs, - moduleLevelPair{moduleAndLevelPair[0], logLevel}) - } else { - if defaultLogLevel >= minLogLevel { - return errors.New("multiple default values found") - } - - level, err := ParseLevel(logLevelByModulePart) - if err != nil { - return err - } - - defaultLogLevel = level - } - } - - if defaultLogLevel >= minLogLevel { - levels.Set("", defaultLogLevel) - } else { - levels.Set("", INFO) - } - - for _, moduleLevelPair := range moduleLevelPairs { - levels.Set(moduleLevelPair.module, moduleLevelPair.logLevel) - } - - return nil -} - -// GetSpec returns the log spec which specifies the log level of each individual module. The spec is -// in the following format: -// -// module1=level1:module2=level2:module3=level3:defaultLevel -// -// Example: -// -// module1=error:module2=debug:module3=warning:info -func GetSpec() string { - var spec string - - var defaultDebugLevel string - - for module, level := range getAllLevels() { - if module == "" { - defaultDebugLevel = level.String() - } else { - spec += fmt.Sprintf("%s=%s:", module, level.String()) - } - } - - return spec + defaultDebugLevel -} - -func getAllLevels() map[string]Level { - metadataLevels := levels.All() - - // Convert to the Level type in this package - levels := make(map[string]Level) - for module, logLevel := range metadataLevels { - levels[module] = logLevel - } - - return levels -} - -type moduleLevelPair struct { - module string - logLevel Level -} - -func newModuleLevels() *moduleLevels { - return &moduleLevels{levels: make(map[string]Level)} -} - -// moduleLevels maintains log levels based on modules. -type moduleLevels struct { - levels map[string]Level - rwmutex sync.RWMutex -} - -// Get returns the log level for given module and level. -func (l *moduleLevels) Get(module string) Level { - l.rwmutex.RLock() - defer l.rwmutex.RUnlock() - - level, exists := l.levels[module] - if !exists { - level, exists = l.levels[defaultModuleName] - // no configuration exists, default to info - if !exists { - return defaultLevel - } - } - - return level -} - -// All returns all set log levels. -func (l *moduleLevels) All() map[string]Level { - l.rwmutex.RLock() - levels := l.levels - l.rwmutex.RUnlock() - - levelsCopy := make(map[string]Level) - - for module, logLevel := range levels { - levelsCopy[module] = logLevel - } - - return levelsCopy -} - -func (l *moduleLevels) Set(module string, level Level) { - l.rwmutex.Lock() - l.levels[module] = level - l.rwmutex.Unlock() -} - -func (l *moduleLevels) SetDefault(level Level) { - l.Set(defaultModuleName, level) -} - -// isEnabled will return true if logging is enabled for given module and level. -func (l *moduleLevels) isEnabled(module string, level Level) bool { - return level >= l.Get(module) -} - -func newZap(module string, encoding Encoding, stdOut, stdErr zapcore.WriteSyncer) *zap.Logger { - encoder := newZapEncoder(encoding) - - core := zapcore.NewTee( - zapcore.NewCore(encoder, zapcore.Lock(stdErr), - zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { - return lvl >= zapcore.ErrorLevel && levels.isEnabled(module, Level(lvl)) - }), - ), - zapcore.NewCore(encoder, zapcore.Lock(stdOut), - zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { - return lvl < zapcore.ErrorLevel && levels.isEnabled(module, Level(lvl)) - }), - ), - ) - - return zap.New(core, zap.AddCaller()).Named(module) -} - -func newZapEncoder(encoding Encoding) zapcore.Encoder { - defaultCfg := zapcore.EncoderConfig{ - TimeKey: timestampKey, - LevelKey: levelKey, - NameKey: moduleKey, - CallerKey: callerKey, - FunctionKey: zapcore.OmitKey, - MessageKey: messageKey, - StacktraceKey: stacktraceKey, - LineEnding: zapcore.DefaultLineEnding, - EncodeLevel: zapcore.CapitalLevelEncoder, - EncodeTime: zapcore.ISO8601TimeEncoder, - EncodeDuration: zapcore.StringDurationEncoder, - EncodeCaller: zapcore.ShortCallerEncoder, - } - - switch strings.ToLower(encoding) { - case JSON: - cfg := defaultCfg - cfg.EncodeLevel = zapcore.LowercaseLevelEncoder - - return zapcore.NewJSONEncoder(cfg) - case Console: - cfg := defaultCfg - cfg.EncodeName = func(moduleName string, encoder zapcore.PrimitiveArrayEncoder) { - encoder.AppendString(fmt.Sprintf("[%s]", moduleName)) - } - - return zapcore.NewConsoleEncoder(cfg) - default: - panic("unsupported encoding " + encoding) - } -} - -func getOptions(opts []Option) *options { - options := &options{ - encoding: DefaultEncoding, - stdOut: os.Stdout, - stdErr: os.Stderr, - } - - for _, opt := range opts { - opt(options) - } - - return options -} diff --git a/internal/pkg/log/logger_test.go b/internal/pkg/log/logger_test.go deleted file mode 100644 index 40ad67c..0000000 --- a/internal/pkg/log/logger_test.go +++ /dev/null @@ -1,344 +0,0 @@ -/* -Copyright SecureKey Technologies Inc. All Rights Reserved. - -SPDX-License-Identifier: Apache-2.0 -*/ - -package log - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/require" -) - -type mockWriter struct { - *bytes.Buffer -} - -func (m *mockWriter) Sync() error { - return nil -} - -func newMockWriter() *mockWriter { - return &mockWriter{Buffer: bytes.NewBuffer(nil)} -} - -func TestLogger(t *testing.T) { - const module = "sample-module" - - t.Run("Default level", func(t *testing.T) { - stdOut := newMockWriter() - stdErr := newMockWriter() - - logger := New(module, WithStdOut(stdOut), WithStdErr(stdErr)) - - logger.Debug("Sample debug log") - logger.Info("Sample info log") - logger.Warn("Sample warn log") - logger.Error("Sample error log") - - require.Panics(t, func() { - logger.Panic("Sample panic log") - }) - - require.NotContains(t, stdOut.Buffer.String(), "DEBUG") - require.Contains(t, stdOut.Buffer.String(), "INFO") - require.Contains(t, stdOut.Buffer.String(), "WARN") - require.NotContains(t, stdOut.Buffer.String(), "PANIC") - require.NotContains(t, stdOut.Buffer.String(), "FATAL") - - require.NotContains(t, stdErr.Buffer.String(), "DEBUG") - require.NotContains(t, stdErr.Buffer.String(), "INFO") - require.NotContains(t, stdErr.Buffer.String(), "WARN") - require.Contains(t, stdErr.Buffer.String(), "ERROR") - require.Contains(t, stdErr.Buffer.String(), "PANIC") - }) - - t.Run("DEBUG", func(t *testing.T) { - SetLevel(module, DEBUG) - - stdOut := newMockWriter() - stdErr := newMockWriter() - - logger := New(module, WithStdOut(stdOut), WithStdErr(stdErr)) - - logger.Debug("Sample debug log") - logger.Info("Sample info log") - logger.Warn("Sample warn log") - logger.Error("Sample error log") - - require.Panics(t, func() { - logger.Panic("Sample panic log") - }) - - require.Contains(t, stdOut.Buffer.String(), "DEBUG") - require.Contains(t, stdOut.Buffer.String(), "INFO") - require.Contains(t, stdOut.Buffer.String(), "WARN") - require.NotContains(t, stdOut.Buffer.String(), "PANIC") - require.NotContains(t, stdOut.Buffer.String(), "FATAL") - - require.NotContains(t, stdErr.Buffer.String(), "DEBUG") - require.NotContains(t, stdErr.Buffer.String(), "INFO") - require.NotContains(t, stdErr.Buffer.String(), "WARN") - require.Contains(t, stdErr.Buffer.String(), "ERROR") - require.Contains(t, stdErr.Buffer.String(), "PANIC") - }) - - t.Run("ERROR", func(t *testing.T) { - SetLevel(module, ERROR) - - stdOut := newMockWriter() - stdErr := newMockWriter() - - logger := New(module, WithStdOut(stdOut), WithStdErr(stdErr)) - - logger.Debug("Sample debug log") - logger.Info("Sample info log") - logger.Warn("Sample warn log") - logger.Error("Sample error log") - - require.Panics(t, func() { - logger.Panic("Sample panic log") - }) - - require.Empty(t, stdOut.Buffer.String()) - - require.NotContains(t, stdErr.Buffer.String(), "DEBUG") - require.NotContains(t, stdErr.Buffer.String(), "INFO") - require.NotContains(t, stdErr.Buffer.String(), "WARN") - require.Contains(t, stdErr.Buffer.String(), "ERROR") - require.Contains(t, stdErr.Buffer.String(), "PANIC") - }) -} - -// TestAllLevels tests logging level behaviour -// logging levels can be set per modules, if not set then it will default to 'INFO'. -func TestAllLevels(t *testing.T) { - module := "sample-module-critical" - - SetLevel(module, FATAL) - require.Equal(t, FATAL, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL}, []Level{PANIC, ERROR, WARNING, INFO, DEBUG}) - - SetLevel(module, PANIC) - require.Equal(t, PANIC, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL, PANIC}, []Level{ERROR, WARNING, INFO, DEBUG}) - - module = "sample-module-error" - SetLevel(module, ERROR) - require.Equal(t, ERROR, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL, PANIC, ERROR}, []Level{WARNING, INFO, DEBUG}) - - module = "sample-module-warning" - SetLevel(module, WARNING) - require.Equal(t, WARNING, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL, PANIC, ERROR, WARNING}, []Level{INFO, DEBUG}) - - module = "sample-module-info" - SetLevel(module, INFO) - require.Equal(t, INFO, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL, PANIC, ERROR, WARNING, INFO}, []Level{DEBUG}) - - module = "sample-module-debug" - SetLevel(module, DEBUG) - require.Equal(t, DEBUG, GetLevel(module)) - verifyLevels(t, module, []Level{FATAL, PANIC, ERROR, WARNING, INFO, DEBUG}, []Level{}) -} - -func TestGetAllLevels(t *testing.T) { - sampleModuleCritical := "sample-module-critical" - SetLevel(sampleModuleCritical, PANIC) - - sampleModuleWarning := "sample-module-warning" - SetLevel(sampleModuleWarning, WARNING) - - allLogLevels := getAllLevels() - require.Equal(t, PANIC, allLogLevels[sampleModuleCritical]) - require.Equal(t, WARNING, allLogLevels[sampleModuleWarning]) -} - -// TestLogLevel testing 'LogLevel()' used for parsing log levels from strings. -func TestLogLevel(t *testing.T) { - verifyLevelsNoError := func(expected Level, levels ...string) { - for _, level := range levels { - actual, err := ParseLevel(level) - require.NoError(t, err, "not supposed to fail while parsing level string [%s]", level) - require.Equal(t, expected, actual) - } - } - - verifyLevelsNoError(FATAL, "fatal", "FATAL") - verifyLevelsNoError(PANIC, "panic", "PANIC") - verifyLevelsNoError(ERROR, "error", "ERROR") - verifyLevelsNoError(WARNING, "warn", "WARN", "warning", "WARNING") - verifyLevelsNoError(DEBUG, "debug", "DEBUG") - verifyLevelsNoError(INFO, "info", "INFO") -} - -// TestParseLevelError testing 'LogLevel()' used for parsing log levels from strings. -func TestParseLevelError(t *testing.T) { - verifyLevelError := func(levels ...string) { - for _, level := range levels { - _, err := ParseLevel(level) - require.Error(t, err, "not supposed to succeed while parsing level string [%s]", level) - } - } - - verifyLevelError("", "D", "DE BUG", ".") -} - -func TestParseString(t *testing.T) { - require.Equal(t, "FATAL", FATAL.String()) - require.Equal(t, "PANIC", PANIC.String()) - require.Equal(t, "ERROR", ERROR.String()) - require.Equal(t, "WARN", WARNING.String()) - require.Equal(t, "INFO", INFO.String()) - require.Equal(t, "DEBUG", DEBUG.String()) -} - -func TestSetSpecLogSpecPut(t *testing.T) { - t.Run("Successfully set logging levels", func(t *testing.T) { - resetLoggingLevels() - - require.NoError(t, SetSpec("module1=debug:module2=panic:error")) - - require.Equal(t, DEBUG, GetLevel("module1")) - require.Equal(t, PANIC, GetLevel("module2")) - require.Equal(t, ERROR, GetLevel("")) - }) - - t.Run("Successfully set logging levels - no default", func(t *testing.T) { - resetLoggingLevels() - - require.NoError(t, SetSpec("module1=debug:module2=panic")) - - require.Equal(t, DEBUG, GetLevel("module1")) - require.Equal(t, PANIC, GetLevel("module2")) - require.Equal(t, INFO, GetLevel("")) - }) - - t.Run("Invalid log spec: default log level type is invalid", func(t *testing.T) { - resetLoggingLevels() - - err := SetSpec("InvalidLogLevel") - require.Error(t, err) - require.Contains(t, err.Error(), "invalid log level") - - // Log levels should remain at the default setting of "info" - require.Equal(t, INFO, GetLevel("module1")) - require.Equal(t, INFO, GetLevel("module2")) - require.Equal(t, INFO, GetLevel("")) - }) - - t.Run("Invalid log spec: module log level type is invalid", func(t *testing.T) { - resetLoggingLevels() - - err := SetSpec("Module1=InvalidLogLevel") - require.Error(t, err) - require.Contains(t, err.Error(), "invalid log level") - - // Log levels should remain at the default setting of "info" - require.Equal(t, INFO, GetLevel("module1")) - require.Equal(t, INFO, GetLevel("module2")) - require.Equal(t, INFO, GetLevel("")) - }) - - t.Run("Invalid log spec: multiple default log levels", func(t *testing.T) { - resetLoggingLevels() - - err := SetSpec("debug:debug") - require.Error(t, err) - require.Contains(t, err.Error(), "multiple default values found") - - // Log levels should remain at the default setting of "info" - require.Equal(t, INFO, GetLevel("module1")) - require.Equal(t, INFO, GetLevel("module2")) - require.Equal(t, INFO, GetLevel("")) - }) -} - -func TestLogSpecGet(t *testing.T) { - resetLoggingLevels() - - spec := GetSpec() - - t.Logf("Got spec: %s", spec) - - require.Contains(t, spec, "module1=INFO") - require.Contains(t, spec, "module2=INFO") - require.Contains(t, spec, ":INFO") -} - -func TestLogLevels(t *testing.T) { - mlevel := newModuleLevels() - - mlevel.Set("module-xyz-info", INFO) - mlevel.Set("module-xyz-debug", DEBUG) - mlevel.Set("module-xyz-error", ERROR) - mlevel.Set("module-xyz-warning", WARNING) - mlevel.Set("module-xyz-panic", PANIC) - - // Run info level checks - require.True(t, mlevel.isEnabled("module-xyz-info", PANIC)) - require.True(t, mlevel.isEnabled("module-xyz-info", ERROR)) - require.True(t, mlevel.isEnabled("module-xyz-info", WARNING)) - require.True(t, mlevel.isEnabled("module-xyz-info", INFO)) - require.False(t, mlevel.isEnabled("module-xyz-info", DEBUG)) - - // Run debug level checks - require.True(t, mlevel.isEnabled("module-xyz-debug", PANIC)) - require.True(t, mlevel.isEnabled("module-xyz-debug", ERROR)) - require.True(t, mlevel.isEnabled("module-xyz-debug", WARNING)) - require.True(t, mlevel.isEnabled("module-xyz-debug", INFO)) - require.True(t, mlevel.isEnabled("module-xyz-debug", DEBUG)) - - // Run warning level checks - require.True(t, mlevel.isEnabled("module-xyz-warning", PANIC)) - require.True(t, mlevel.isEnabled("module-xyz-warning", ERROR)) - require.True(t, mlevel.isEnabled("module-xyz-warning", WARNING)) - require.False(t, mlevel.isEnabled("module-xyz-warning", INFO)) - require.False(t, mlevel.isEnabled("module-xyz-warning", DEBUG)) - - // Run error level checks - require.True(t, mlevel.isEnabled("module-xyz-error", PANIC)) - require.True(t, mlevel.isEnabled("module-xyz-error", ERROR)) - require.False(t, mlevel.isEnabled("module-xyz-error", WARNING)) - require.False(t, mlevel.isEnabled("module-xyz-error", INFO)) - require.False(t, mlevel.isEnabled("module-xyz-error", DEBUG)) - - // Run error panic checks - require.True(t, mlevel.isEnabled("module-xyz-panic", PANIC)) - require.False(t, mlevel.isEnabled("module-xyz-panic", ERROR)) - require.False(t, mlevel.isEnabled("module-xyz-panic", WARNING)) - require.False(t, mlevel.isEnabled("module-xyz-panic", INFO)) - require.False(t, mlevel.isEnabled("module-xyz-panic", DEBUG)) - - // Run default log level check --> which is info level - require.True(t, mlevel.isEnabled("module-xyz-random-module", PANIC)) - require.True(t, mlevel.isEnabled("module-xyz-random-module", ERROR)) - require.True(t, mlevel.isEnabled("module-xyz-random-module", WARNING)) - require.True(t, mlevel.isEnabled("module-xyz-random-module", INFO)) - require.False(t, mlevel.isEnabled("module-xyz-random-module", DEBUG)) -} - -func resetLoggingLevels() { - SetLevel("module1", INFO) - SetLevel("module2", INFO) - SetDefaultLevel(INFO) -} - -func verifyLevels(t *testing.T, module string, enabled, disabled []Level) { - t.Helper() - - for _, level := range enabled { - require.True(t, levels.isEnabled(module, level), - "expected level [%s] to be enabled for module [%s]", level, module) - } - - for _, level := range disabled { - require.False(t, levels.isEnabled(module, level), - "expected level [%s] to be disabled for module [%s]", level, module) - } -} diff --git a/internal/pkg/tlsutil/certpool.go b/internal/pkg/tlsutil/certpool.go index cf2fdd8..4aed85f 100644 --- a/internal/pkg/tlsutil/certpool.go +++ b/internal/pkg/tlsutil/certpool.go @@ -10,7 +10,9 @@ import ( "sync" "sync/atomic" - "github.com/trustbloc/vct/internal/pkg/log" + "github.com/trustbloc/logutil-go/pkg/log" + + logfields "github.com/trustbloc/vct/internal/pkg/log" ) var logger = log.New("tlsutil") @@ -157,7 +159,7 @@ func loadSystemCertPool(useSystemCertPool bool) (*x509.CertPool, error) { return nil, err } - logger.Debug("Loaded system cert pool", log.WithSize(len(systemCertPool.Subjects()))) + logger.Debug("Loaded system cert pool", logfields.WithSize(len(systemCertPool.Subjects()))) return systemCertPool, nil } diff --git a/pkg/controller/rest/operation.go b/pkg/controller/rest/operation.go index 68358af..7d9ae3a 100644 --- a/pkg/controller/rest/operation.go +++ b/pkg/controller/rest/operation.go @@ -20,8 +20,8 @@ import ( "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/trustbloc/logutil-go/pkg/log" - "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/pkg/controller/command" "github.com/trustbloc/vct/pkg/controller/errors" ) diff --git a/pkg/log/log.go b/pkg/log/log.go index dd51447..04ebbeb 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -7,7 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package log import ( - "github.com/trustbloc/vct/internal/pkg/log" + "github.com/trustbloc/logutil-go/pkg/log" ) // SetLevel sets the log level for given module and level. diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 06d5f5a..af369dc 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -10,8 +10,7 @@ import ( "testing" "github.com/stretchr/testify/require" - - "github.com/trustbloc/vct/internal/pkg/log" + "github.com/trustbloc/logutil-go/pkg/log" ) func TestDefaultLevel(t *testing.T) { diff --git a/pkg/storage/postgres/admin_storage.go b/pkg/storage/postgres/admin_storage.go index 636c69a..ba1ac4e 100644 --- a/pkg/storage/postgres/admin_storage.go +++ b/pkg/storage/postgres/admin_storage.go @@ -21,12 +21,11 @@ import ( "github.com/google/trillian" "github.com/google/trillian/storage" + "github.com/trustbloc/logutil-go/pkg/log" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" - - "github.com/trustbloc/vct/internal/pkg/log" ) var logger = log.New("storage/postgres") diff --git a/pkg/storage/postgres/log_storage.go b/pkg/storage/postgres/log_storage.go index 5b55b45..5ca55eb 100644 --- a/pkg/storage/postgres/log_storage.go +++ b/pkg/storage/postgres/log_storage.go @@ -31,10 +31,11 @@ import ( "github.com/google/trillian/storage/cache" trilliantree "github.com/google/trillian/storage/tree" "github.com/google/trillian/types" - "github.com/trustbloc/vct/internal/pkg/log" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/timestamppb" + + logfields "github.com/trustbloc/vct/internal/pkg/log" ) // nolint: lll @@ -518,7 +519,7 @@ func (t *logTreeTX) QueueLeaves(ctx context.Context, leaves []*trillian.LogLeaf, existingCount++ queuedDupCounter.Inc(label) - logger.Warn("Found duplicate", log.WithTreeID(t.treeID), log.WithLeaf(leaf)) + logger.Warn("Found duplicate", logfields.WithTreeID(t.treeID), logfields.WithLeaf(leaf)) continue } @@ -819,9 +820,11 @@ func (t *logTreeTX) StoreSignedLogRoot(ctx context.Context, root *trillian.Signe if len(logRoot.Metadata) != 0 { return fmt.Errorf("unimplemented: postgres storage does not support log root metadata") } + // get a json copy of the tree_head data, _ := json.Marshal(logRoot) // nolint: errcheck - t.tx.ExecContext( // nolint: errcheck,gosec + + t.tx.ExecContext( // nolint: errcheck,gosec ctx, "update trees set current_tree_data = $1,root_signature = $2 where tree_id = $3", data, diff --git a/pkg/storage/postgres/testdb/testdb.go b/pkg/storage/postgres/testdb/testdb.go index 8dba308..2c441eb 100644 --- a/pkg/storage/postgres/testdb/testdb.go +++ b/pkg/storage/postgres/testdb/testdb.go @@ -24,8 +24,9 @@ import ( "time" "github.com/google/trillian/testonly" + "github.com/trustbloc/logutil-go/pkg/log" - "github.com/trustbloc/vct/internal/pkg/log" + logfields "github.com/trustbloc/vct/internal/pkg/log" ) var logger = log.New("storage/testdb") @@ -83,7 +84,7 @@ func newEmptyDB(ctx context.Context) (*sql.DB, func(context.Context), error) { db, err = sql.Open("postgres", getConnStr("test")) if _, err := db.ExecContext(ctx, fmt.Sprintf("DROP DATABASE %v WITH (FORCE);", name)); err != nil { - logger.Warn("Failed to drop test database", log.WithStore(name), log.WithError(err)) + logger.Warn("Failed to drop test database", logfields.WithStore(name), log.WithError(err)) } db.Close() // nolint: errcheck, gosec diff --git a/test/bdd/bddtests_test.go b/test/bdd/bddtests_test.go index 40c6f4e..60a9239 100644 --- a/test/bdd/bddtests_test.go +++ b/test/bdd/bddtests_test.go @@ -15,8 +15,9 @@ import ( "time" "github.com/cucumber/godog" + "github.com/trustbloc/logutil-go/pkg/log" - "github.com/trustbloc/vct/internal/pkg/log" + logfields "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/test/bdd/pkg/controller/rest" ) @@ -66,18 +67,18 @@ var ( func runBddTests(tags, format string) int { return godog.RunWithOptions("godogs", func(s *godog.Suite) { s.BeforeSuite(func() { - logger.Info("Running command", log.WithCommand(strings.Join(dockerComposeUp, " "))) + logger.Info("Running command", logfields.WithCommand(strings.Join(dockerComposeUp, " "))) if err := exec.Command(dockerComposeUp[0], dockerComposeUp[1:]...).Run(); err != nil { //nolint: gosec - logger.Error("Command", log.WithCommand(strings.Join(dockerComposeUp, " ")), + logger.Error("Command", logfields.WithCommand(strings.Join(dockerComposeUp, " ")), log.WithError(err)) } }) s.AfterSuite(func() { - logger.Info("Running command", log.WithCommand(strings.Join(dockerComposeDown, " "))) + logger.Info("Running command", logfields.WithCommand(strings.Join(dockerComposeDown, " "))) if err := exec.Command(dockerComposeDown[0], dockerComposeDown[1:]...).Run(); err != nil { //nolint: gosec - logger.Error("Command failed", log.WithCommand(strings.Join(dockerComposeDown, " ")), + logger.Error("Command failed", logfields.WithCommand(strings.Join(dockerComposeDown, " ")), log.WithError(err)) } }) diff --git a/test/bdd/pkg/controller/rest/rest_controller_steps.go b/test/bdd/pkg/controller/rest/rest_controller_steps.go index 0fbaae4..9e3210c 100644 --- a/test/bdd/pkg/controller/rest/rest_controller_steps.go +++ b/test/bdd/pkg/controller/rest/rest_controller_steps.go @@ -25,9 +25,10 @@ import ( "github.com/hyperledger/aries-framework-go/pkg/doc/ld" "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext" ldstore "github.com/hyperledger/aries-framework-go/pkg/store/ld" + "github.com/trustbloc/logutil-go/pkg/log" vcldcontext "github.com/trustbloc/vct/internal/pkg/ldcontext" - "github.com/trustbloc/vct/internal/pkg/log" + logfields "github.com/trustbloc/vct/internal/pkg/log" "github.com/trustbloc/vct/pkg/client/vct" "github.com/trustbloc/vct/pkg/controller/command" ) @@ -243,9 +244,9 @@ func (s *Steps) addVC(file string) error { s.state.AddedCredentials[file] = resp - logger.Info("Successfully verified VC timestamp signature", log.WithVerifiableCredential(src), - log.WithSignature(resp.Signature), log.WithTimestamp(resp.Timestamp), - log.WithPublicKey(webResp.Properties[command.PublicKeyType])) + logger.Info("Successfully verified VC timestamp signature", logfields.WithVerifiableCredential(src), + logfields.WithSignature(resp.Signature), logfields.WithTimestamp(resp.Timestamp), + logfields.WithPublicKey(webResp.Properties[command.PublicKeyType])) return nil }