From 4a3d7af577b52b9598942cc8ac4526441c80acce Mon Sep 17 00:00:00 2001 From: Daniel Pupius Date: Tue, 21 May 2024 17:48:35 -0700 Subject: [PATCH] Remove logrus in-favor of log/slog --- .golangci.yaml | 2 +- Makefile | 8 ++++---- generator/generator.go | 10 +++++----- generator/template.go | 5 ++--- go.mod | 2 -- go.sum | 9 --------- main.go | 34 ++++++++++++++++++++-------------- registry/file.go | 16 +++++++++------- registry/registry.go | 25 +++++++++++++------------ 9 files changed, 54 insertions(+), 57 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index add8ff9..b3b4185 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -192,7 +192,7 @@ linters-settings: # - "all": report all global loggers # - "default": report only the default slog logger # Default: "" - no-global: "all" + no-global: "" # Enforce using methods that accept a context. # Values: # - "": disabled diff --git a/Makefile b/Makefile index 99cd993..4c8f5ce 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ integration-test-client: build ## Generates the typescript client code used by e -I ../ \ --grpc-gateway-ts_out ./test/integration/defaultConfig \ --grpc-gateway-ts_opt logtostderr=true \ - --grpc-gateway-ts_opt loglevel=debug \ + --grpc-gateway-ts_opt loglevel=info \ --grpc-gateway-ts_opt use_proto_names=false \ --grpc-gateway-ts_opt emit_unpopulated=false \ --grpc-gateway-ts_opt enable_styling_check=true \ @@ -67,7 +67,7 @@ integration-test-client: build ## Generates the typescript client code used by e -I ../ \ --grpc-gateway-ts_out ./test/integration/useProtoNames \ --grpc-gateway-ts_opt logtostderr=true \ - --grpc-gateway-ts_opt loglevel=debug \ + --grpc-gateway-ts_opt loglevel=info \ --grpc-gateway-ts_opt use_proto_names=true \ --grpc-gateway-ts_opt emit_unpopulated=false \ --grpc-gateway-ts_opt enable_styling_check=true \ @@ -79,7 +79,7 @@ integration-test-client: build ## Generates the typescript client code used by e -I ../ \ --grpc-gateway-ts_out ./test/integration/emitUnpopulated \ --grpc-gateway-ts_opt logtostderr=true \ - --grpc-gateway-ts_opt loglevel=debug \ + --grpc-gateway-ts_opt loglevel=info \ --grpc-gateway-ts_opt use_proto_names=false \ --grpc-gateway-ts_opt emit_unpopulated=true \ --grpc-gateway-ts_opt enable_styling_check=true \ @@ -91,7 +91,7 @@ integration-test-client: build ## Generates the typescript client code used by e -I ../ \ --grpc-gateway-ts_out ./test/integration/noStaticClasses \ --grpc-gateway-ts_opt logtostderr=true \ - --grpc-gateway-ts_opt loglevel=debug \ + --grpc-gateway-ts_opt loglevel=info \ --grpc-gateway-ts_opt use_proto_names=false \ --grpc-gateway-ts_opt emit_unpopulated=false \ --grpc-gateway-ts_opt enable_styling_check=true \ diff --git a/generator/generator.go b/generator/generator.go index ccbae7c..a186d2b 100644 --- a/generator/generator.go +++ b/generator/generator.go @@ -3,11 +3,11 @@ package generator import ( "bytes" "fmt" + "log/slog" "path/filepath" "strings" "text/template" - log "github.com/sirupsen/logrus" //nolint: depguard // Need to remove "google.golang.org/protobuf/types/pluginpb" "github.com/dpup/protoc-gen-grpc-gateway-ts/registry" @@ -37,17 +37,17 @@ func (t *TypeScriptGRPCGatewayGenerator) Generate( return nil, errors.Wrap(err, "error analysing proto files") } tmpl := ServiceTemplate(t.Registry) - log.Debugf("files to generate %v", req.GetFileToGenerate()) + slog.Debug("generating files", slog.Any("files", req.GetFileToGenerate())) requiresFetchModule := false // feed fileData into rendering process for _, fileData := range filesData { if !t.Registry.IsFileToGenerate(fileData.Name) { - log.Debugf("file %s is not the file to generate, skipping", fileData.Name) + slog.Debug("file is not the file to generate, skipping", slog.String("fileName", fileData.Name)) continue } - log.Debugf("generating file for %s", fileData.TSFileName) + slog.Debug("generating file", slog.String("fileName", fileData.TSFileName)) data := &TemplateData{ File: fileData, EnableStylingCheck: t.Registry.EnableStylingCheck, @@ -63,7 +63,7 @@ func (t *TypeScriptGRPCGatewayGenerator) Generate( if requiresFetchModule { fetchTmpl := FetchModuleTemplate() - log.Debugf("generate fetch template") + slog.Debug("generate fetch template") generatedFetch, err := t.generateFetchModule(fetchTmpl) if err != nil { return nil, errors.Wrap(err, "error generating fetch module") diff --git a/generator/template.go b/generator/template.go index 86178a6..c1baeb4 100644 --- a/generator/template.go +++ b/generator/template.go @@ -3,13 +3,12 @@ package generator import ( "bytes" "fmt" + "log/slog" "net/url" "regexp" "strings" "text/template" - log "github.com/sirupsen/logrus" - "github.com/Masterminds/sprig" "github.com/dpup/protoc-gen-grpc-gateway-ts/data" @@ -86,7 +85,7 @@ func renderURL(r *registry.Registry) func(method data.Method) string { matches := reg.FindAllStringSubmatch(methodURL, -1) fieldsInPath := make([]string, 0, len(matches)) if len(matches) > 0 { - log.Debugf("url matches %v", matches) + slog.Debug("url matches", slog.Any("matches", matches)) for _, m := range matches { expToReplace := m[0] fieldName := fieldNameFn(m[1]) diff --git a/go.mod b/go.mod index 94f9b02..f452271 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,9 @@ go 1.22 require ( github.com/Masterminds/sprig v2.22.0+incompatible - github.com/golang/protobuf v1.5.4 github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 github.com/iancoleman/strcase v0.3.0 github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.9.0 google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be google.golang.org/grpc v1.63.2 diff --git a/go.sum b/go.sum index 1adcfc1..7eeb490 100644 --- a/go.sum +++ b/go.sum @@ -5,11 +5,8 @@ github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF0 github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= 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/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -36,17 +33,12 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= @@ -64,6 +56,5 @@ google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHh gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -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= diff --git a/main.go b/main.go index 0298692..8924798 100644 --- a/main.go +++ b/main.go @@ -4,12 +4,12 @@ import ( "flag" "fmt" "io" + "log/slog" "os" "strings" "github.com/dpup/protoc-gen-grpc-gateway-ts/generator" "github.com/dpup/protoc-gen-grpc-gateway-ts/registry" - log "github.com/sirupsen/logrus" //nolint: depguard // need to remove "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/pluginpb" ) @@ -73,7 +73,7 @@ func run() error { return fmt.Errorf("error instantiating a new generator: %w", err) } - log.Debug("Starts generating file request") + slog.Debug("Starts generating file request") resp, err := g.Generate(req) if err != nil { @@ -85,27 +85,33 @@ func run() error { encodeResponse(resp) - log.Debug("generation finished") + slog.Debug("generation finished") return nil } func configureLogging(enableLogging bool, levelStr string) error { if enableLogging { - log.SetFormatter(&log.TextFormatter{ - DisableTimestamp: true, - }) - log.SetOutput(os.Stderr) - log.Debugf("Logging configured completed, logging has been enabled") + level := slog.LevelInfo if levelStr != "" { - level, err := log.ParseLevel(levelStr) - if err != nil { - return fmt.Errorf("error parsing log level %s: %w", levelStr, err) + switch levelStr { + case "debug": + level = slog.LevelDebug + case "info": + level = slog.LevelInfo + case "warn": + level = slog.LevelWarn + case "error": + level = slog.LevelError + default: + return fmt.Errorf("invalid log level %s", levelStr) } - log.SetLevel(level) - } else { - log.SetLevel(log.InfoLevel) } + opts := &slog.HandlerOptions{Level: level} + logger := slog.New(slog.NewTextHandler(os.Stderr, opts)) + slog.SetDefault(logger) + } else { + slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil))) } return nil } diff --git a/registry/file.go b/registry/file.go index 5eac2e8..1949292 100644 --- a/registry/file.go +++ b/registry/file.go @@ -1,19 +1,20 @@ package registry import ( + "fmt" + "log/slog" "path/filepath" "strings" "github.com/dpup/protoc-gen-grpc-gateway-ts/data" "github.com/dpup/protoc-gen-grpc-gateway-ts/options" "github.com/pkg/errors" - log "github.com/sirupsen/logrus" //nolint: depguard // Need to remove "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/descriptorpb" ) func (r *Registry) analyseFile(f *descriptorpb.FileDescriptorProto) (*data.File, error) { - log.Debugf("analysing %s", f.GetName()) + slog.Debug("analysing file", slog.String("filename", f.GetName())) fileData := data.NewFile() fileName := f.GetName() packageName := f.GetPackage() @@ -52,7 +53,7 @@ func (r *Registry) analyseFile(f *descriptorpb.FileDescriptorProto) (*data.File, func (r *Registry) addFetchModuleDependencies(fileData *data.File) error { if !fileData.Services.RequiresFetchModule() { - log.Debugf("no services found for %s, skipping fetch module", fileData.Name) + slog.Debug("no services found for, skipping fetch module", slog.String("name", fileData.Name)) return nil } @@ -75,7 +76,7 @@ func (r *Registry) addFetchModuleDependencies(fileData *data.File) error { return errors.Wrapf(err, "error replacing source file with alias for %s", fileName) } - log.Debugf("added fetch dependency %s for %s", sourceFile, fileData.TSFileName) + slog.Debug("added fetch dependency %s for %s", sourceFile, fileData.TSFileName) fileData.AddDependency(&data.Dependency{ ModuleIdentifier: "fm", SourceFile: sourceFile, @@ -92,7 +93,8 @@ func (r *Registry) analyseFilePackageTypeDependencies(fileData *data.File) { // also need to change the type's IsExternal information for rendering purpose typeInfo := t.GetType() fqTypeName := typeInfo.Type - log.Debugf("checking whether non scala type %s in the same message is external to the current file", fqTypeName) + slog.Debug("checking whether non scala type in the same message is external to the current file", + slog.Any("type", fqTypeName)) registryType, foundInRegistry := r.Types[fqTypeName] if !foundInRegistry || registryType.File != fileData.Name { @@ -100,8 +102,8 @@ func (r *Registry) analyseFilePackageTypeDependencies(fileData *data.File) { // or the type has appeared in another file different to the current file // in this case we will put the type as external in the fileData // and also mutate the IsExternal field of the given type:w - log.Debugf("type %s is external to file %s, mutating the external dependencies information", - fqTypeName, fileData.Name) + slog.Debug(fmt.Sprintf("type %s is external to file %s, mutating the external dependencies information", + fqTypeName, fileData.Name)) fileData.ExternalDependingTypes = append(fileData.ExternalDependingTypes, fqTypeName) t.SetExternal(true) diff --git a/registry/registry.go b/registry/registry.go index bd6e479..c365923 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -1,6 +1,8 @@ package registry import ( + "fmt" + "log/slog" "os" "path" "path/filepath" @@ -8,7 +10,6 @@ import ( "github.com/dpup/protoc-gen-grpc-gateway-ts/data" "github.com/pkg/errors" - log "github.com/sirupsen/logrus" //nolint: depguard // not sure, will remove "google.golang.org/protobuf/types/descriptorpb" "google.golang.org/protobuf/types/pluginpb" ) @@ -65,14 +66,14 @@ type Registry struct { // NewRegistry initialise the registry and return the instance. func NewRegistry(opts Options) (*Registry, error) { tsImportRoots, tsImportRootAliases, err := getTSImportRootInformation(opts) - log.Debugf("found ts import roots %v", tsImportRoots) - log.Debugf("found ts import root aliases %v", tsImportRootAliases) + slog.Debug("found ts import roots", slog.Any("importRoots", tsImportRoots)) + slog.Debug("found ts import root aliases", slog.Any("importRootAliases", tsImportRootAliases)) if err != nil { return nil, errors.Wrap(err, "error getting common import root information") } - log.Debugf("found fetch module directory %s", opts.FetchModuleDirectory) - log.Debugf("found fetch module name %s", opts.FetchModuleFilename) + slog.Debug("found fetch module directory", slog.String("moduleDir", opts.FetchModuleDirectory)) + slog.Debug("found fetch module name", slog.String("moduleName", opts.FetchModuleFilename)) return &Registry{ Options: opts, @@ -161,7 +162,7 @@ func (r *Registry) Analyse(req *pluginpb.CodeGeneratorRequest) (map[string]*data } files := req.GetProtoFile() - log.Debugf("about to start anaylyse files, %d in total", len(files)) + slog.Debug("about to start anaylyse files", slog.Int("count", len(files))) data := make(map[string]*data.File) // analyse all files in the request first for _, f := range files { @@ -258,9 +259,9 @@ func (r *Registry) getSourceFileForImport(source, target, root, alias string) (s } ret = strings.ReplaceAll(absTarget, absRoot, alias) - log.Debugf("replacing root alias %s for %s, result: %s", alias, target, ret) + slog.Debug(fmt.Sprintf("replacing root alias %s for %s, result: %s", alias, target, ret)) } else { // return relative path here - log.Debugf("no root alias found, trying to get the relative path for %s", target) + slog.Debug("no root alias found, trying to get the relative path", slog.String("target", target)) absSource, err := filepath.Abs(source) if err != nil { return "", errors.Wrapf(err, "error looking up absolute directory with base dir: %s", source) @@ -272,14 +273,14 @@ func (r *Registry) getSourceFileForImport(source, target, root, alias string) (s } slashPath := filepath.ToSlash(ret) - log.Debugf("got relative path %s for %s", target, slashPath) + slog.Debug(fmt.Sprintf("got relative path %s for %s", target, slashPath)) // sub directory will not have relative path ./, if this happens, prepend one if !strings.HasPrefix(slashPath, "../") { ret = filepath.FromSlash("./" + slashPath) } - log.Debugf("no root alias found, trying to get the relative path for %s, result: %s", target, ret) + slog.Debug(fmt.Sprintf("no root alias found, trying to get the relative path for %s, result: %s", target, ret)) } // remove .ts suffix if there's any @@ -293,7 +294,7 @@ func (r *Registry) getSourceFileForImport(source, target, root, alias string) (s func (r *Registry) collectExternalDependenciesFromData(filesData map[string]*data.File) error { for _, fileData := range filesData { - log.Debugf("collecting dependencies information for %s", fileData.TSFileName) + slog.Debug("collecting dependencies information", slog.String("fileName", fileData.TSFileName)) // dependency group up the dependency by package+file dependencies := make(map[string]*data.Dependency) for _, typeName := range fileData.ExternalDependingTypes { @@ -318,7 +319,7 @@ func (r *Registry) collectExternalDependenciesFromData(filesData map[string]*dat target := data.GetTSFileName(typeInfo.File) var sourceFile string if pkg, ok := r.TSPackages[target]; ok { - log.Debugf("package import override %s has been found for file %s", pkg, target) + slog.Debug("package import override has been found", slog.String("pkg", pkg), slog.String("target", target)) sourceFile = pkg } else { foundAtRoot, alias, err := r.findRootAliasForPath(func(absRoot string) (bool, error) {