diff --git a/tool/cmd/kitex/args/args.go b/tool/cmd/kitex/args/args.go index b609dd3249..9a0aa7c3c3 100644 --- a/tool/cmd/kitex/args/args.go +++ b/tool/cmd/kitex/args/args.go @@ -29,7 +29,6 @@ import ( "strings" "time" - "github.com/cloudwego/kitex/pkg/klog" "github.com/cloudwego/kitex/tool/internal_pkg/generator" "github.com/cloudwego/kitex/tool/internal_pkg/log" "github.com/cloudwego/kitex/tool/internal_pkg/pluginmode/protoc" @@ -306,7 +305,7 @@ func (a *Arguments) checkPath(curpath string) error { goMod, goModPath, hasGoMod := util.SearchGoMod(curpath) if usingGOPATH && a.ModuleName == "" && !hasGoMod { - log.Warn("[Warn] You're relying on $GOPATH for generating code.\n" + + log.Warn("You're relying on $GOPATH for generating code.\n" + "Please add go.mod or specify -module for module path.\n" + "We will deprecate $GOPATH support in the near future!") } @@ -370,7 +369,8 @@ func (a *Arguments) BuildCmd(out io.Writer) (*exec.Cmd, error) { } } - kas := strings.Join(a.Config.Pack(), ",") + configkv := a.Config.Pack() + kas := strings.Join(configkv, ",") cmd := &exec.Cmd{ Path: LookupTool(a.IDLType, a.CompilerPath), Stdin: os.Stdin, @@ -453,7 +453,8 @@ func (a *Arguments) BuildCmd(out io.Writer) (*exec.Cmd, error) { cmd.Args = append(cmd.Args, a.IDL) } - log.Info(strings.ReplaceAll(strings.Join(cmd.Args, " "), kas, fmt.Sprintf("%q", kas))) + log.Debugf("cmd.Args %v", cmd.Args) + log.Debugf("config pairs %v", configkv) return cmd, nil } @@ -525,11 +526,11 @@ func versionSatisfied(current, required string) bool { var currentSeg, minimalSeg int var err error if currentSeg, err = strconv.Atoi(currentSegments[i]); err != nil { - klog.Warnf("invalid current version: %s, seg=%v, err=%v", current, currentSegments[i], err) + log.Warnf("invalid current version: %s, seg=%v, err=%v", current, currentSegments[i], err) return false } if minimalSeg, err = strconv.Atoi(requiredSegments[i]); err != nil { - klog.Warnf("invalid required version: %s, seg=%v, err=%v", required, requiredSegments[i], err) + log.Warnf("invalid required version: %s, seg=%v, err=%v", required, requiredSegments[i], err) return false } if currentSeg > minimalSeg { @@ -551,7 +552,7 @@ func LookupTool(idlType, compilerPath string) string { tool = "protoc" } if compilerPath != "" { - log.Infof("Will use the specified %s: %s\n", tool, compilerPath) + log.Debugf("Will use the specified %s: %s\n", tool, compilerPath) return compilerPath } diff --git a/tool/cmd/kitex/main.go b/tool/cmd/kitex/main.go index a1530837c7..de4dcf0c44 100644 --- a/tool/cmd/kitex/main.go +++ b/tool/cmd/kitex/main.go @@ -16,6 +16,7 @@ package main import ( "bytes" + "errors" "flag" "os" "path/filepath" @@ -56,7 +57,7 @@ func init() { Version: "v0.11.0", }, ); err != nil { - log.Warn(err) + log.Error(err) os.Exit(versions.CompatibilityCheckExitCode) } } @@ -75,17 +76,17 @@ func main() { curpath, err := filepath.Abs(".") if err != nil { - log.Warn("Get current path failed:", err.Error()) + log.Errorf("Get current path failed: %s", err) os.Exit(1) } // run as kitex err = args.ParseArgs(kitex.Version, curpath, os.Args[1:]) if err != nil { - if err.Error() != "flag: help requested" { - log.Warn(err.Error()) - os.Exit(2) + if errors.Is(err, flag.ErrHelp) { + os.Exit(0) } - os.Exit(0) + log.Error(err) + os.Exit(2) } if !args.NoDependencyCheck { // check dependency compatibility between kitex cmd tool and dependency in go.mod diff --git a/tool/cmd/kitex/sdk/kitex_sdk.go b/tool/cmd/kitex/sdk/kitex_sdk.go index 1cd6e3d445..4411a06aab 100644 --- a/tool/cmd/kitex/sdk/kitex_sdk.go +++ b/tool/cmd/kitex/sdk/kitex_sdk.go @@ -16,6 +16,7 @@ package sdk import ( "bytes" + "errors" "flag" "fmt" "os/exec" @@ -33,7 +34,7 @@ import ( var args kargs.Arguments -var errExitZero = fmt.Errorf("os.Exit(0)") +var errExitZero = errors.New("os.Exit(0)") func init() { var queryVersion bool @@ -55,7 +56,7 @@ func init() { func RunKitexTool(wd string, plugins []plugin.SDKPlugin, kitexArgs ...string) error { kitexPlugin, err := GetKiteXSDKPlugin(wd, kitexArgs) if err != nil { - if err.Error() == "flag: help requested" || err == errExitZero { + if errors.Is(err, flag.ErrHelp) || errors.Is(err, errExitZero) { return nil } return err @@ -101,16 +102,11 @@ func InvokeThriftgoBySDK(pwd string, cmd *exec.Cmd) (err error) { kitexPlugin.Pwd = pwd - s := []plugin.SDKPlugin{kitexPlugin} - - err = sdk.RunThriftgoAsSDK(pwd, s, kitexPlugin.GetThriftgoParameters()...) - // when execute thriftgo as function, log will be unexpectedly replaced (for old code by design), so we have to change it back. - log.SetDefaultLogger(log.Logger{ - Println: fmt.Fprintln, - Printf: fmt.Fprintf, - }) - - return err + l := log.DefaultLogger() // pluginmode/thriftgo/convertor.go will change the logger + defer log.SetDefaultLogger(l) // revert it back + return sdk.RunThriftgoAsSDK(pwd, + []plugin.SDKPlugin{kitexPlugin}, + kitexPlugin.GetThriftgoParameters()...) } type KiteXSDKPlugin struct { diff --git a/tool/cmd/kitex/utils/utils.go b/tool/cmd/kitex/utils/utils.go index 3b257d462e..f24378aefc 100644 --- a/tool/cmd/kitex/utils/utils.go +++ b/tool/cmd/kitex/utils/utils.go @@ -24,7 +24,7 @@ import ( ) func OnKitexToolNormalExit(args kargs.Arguments) { - log.Warn("Code Generation is Done!") + log.Info("Code Generation is Done!") if args.IDLType == "thrift" { cmd := "go mod edit -replace github.com/apache/thrift=github.com/apache/thrift@v0.13.0" diff --git a/tool/cmd/kitex/versions/dependencies.go b/tool/cmd/kitex/versions/dependencies.go index c552b83dd5..2113d1c81a 100644 --- a/tool/cmd/kitex/versions/dependencies.go +++ b/tool/cmd/kitex/versions/dependencies.go @@ -78,7 +78,7 @@ func DefaultCheckDependencyAndProcess() error { } res, shouldExit := defaultParseCheckResult(cr) if res != "" { - log.Warn(res) + log.Info(res) } if shouldExit { return errors.New("kitex cmd tool dependency compatibility check failed") diff --git a/tool/internal_pkg/generator/completor.go b/tool/internal_pkg/generator/completor.go index 154b7caac0..03d07814c3 100644 --- a/tool/internal_pkg/generator/completor.go +++ b/tool/internal_pkg/generator/completor.go @@ -83,7 +83,7 @@ func (c *completer) compare(pkg *ast.Package) []*MethodInfo { } } if !have { - log.Infof("[complete handler] add '%s' to handler.go\n", m.Name) + log.Debugf("[complete handler] add '%s' to handler.go\n", m.Name) newMethods = append(newMethods, m) } } @@ -159,8 +159,10 @@ func (c *completer) process(w io.Writer) error { fset := token.NewFileSet() pkgs, err := parser.ParseDir(fset, filepath.Dir(c.handlerPath), nil, parser.ParseComments) if err != nil { - err = fmt.Errorf("go/parser failed to parse the main package: %w", err) - log.Warn("NOTICE: This is not a bug. We cannot add new methods to handler.go because your codes failed to compile. Fix the compile errors and try again.\n%s", err.Error()) + log.Warnf("This is not a bug. \n"+ + "We cannot add new methods to handler.go because your codes failed to compile. \n"+ + "Fix the compile errors and try again.\n"+ + "go/parser err: %s", err) return err } main, ok := pkgs["main"] diff --git a/tool/internal_pkg/generator/custom_template.go b/tool/internal_pkg/generator/custom_template.go index 3f364589db..4b790e6192 100644 --- a/tool/internal_pkg/generator/custom_template.go +++ b/tool/internal_pkg/generator/custom_template.go @@ -129,7 +129,7 @@ func (c *customGenerator) commonGenerate(tpl *Template) error { filePath := filepath.Join(c.basePath, renderPath) update := util.Exists(filePath) if update && updateType(tpl.UpdateBehavior.Type) == skip { - log.Infof("skip generate file %s", tpl.Path) + log.Debugf("skip generate file %s", tpl.Path) return nil } var f *File diff --git a/tool/internal_pkg/generator/generator.go b/tool/internal_pkg/generator/generator.go index 885b1f8945..d150ca7bec 100644 --- a/tool/internal_pkg/generator/generator.go +++ b/tool/internal_pkg/generator/generator.go @@ -377,7 +377,7 @@ func (g *generator) GenerateMainPackage(pkg *PackageInfo) (fs []*File, err error } for _, t := range tasks { if util.Exists(t.Path) { - log.Info(t.Path, "exists. Skipped.") + log.Debug(t.Path, "exists. Skipped.") continue } g.setImports(t.Name, pkg) diff --git a/tool/internal_pkg/log/log.go b/tool/internal_pkg/log/log.go index 699e8dd66b..106d5bbb9d 100644 --- a/tool/internal_pkg/log/log.go +++ b/tool/internal_pkg/log/log.go @@ -16,7 +16,7 @@ package log import ( "fmt" - "io" + "log" "os" ) @@ -24,14 +24,23 @@ import ( var Verbose bool // Logger . -type Logger struct { - Println func(w io.Writer, a ...interface{}) (n int, err error) - Printf func(w io.Writer, format string, a ...interface{}) (n int, err error) +type Logger interface { + Printf(format string, a ...interface{}) } -var defaultLogger = Logger{ - Println: fmt.Fprintln, - Printf: fmt.Fprintf, +// LoggerFunc implements Logger +type LoggerFunc func(format string, a ...interface{}) + +func (f LoggerFunc) Printf(format string, a ...interface{}) { + f(format, a...) +} + +// must use os.Stderr, os.Stdout is used by plugin for output +var defaultLogger Logger = log.New(os.Stderr, "", 0) + +// DefaultLogger ... +func DefaultLogger() Logger { + return defaultLogger } // SetDefaultLogger sets the default logger. @@ -39,26 +48,48 @@ func SetDefaultLogger(l Logger) { defaultLogger = l } -// Warn . +// Error ... +func Error(v ...interface{}) { + defaultLogger.Printf("[ERROR] %s", fmt.Sprintln(v...)) +} + +// Errorf ... +func Errorf(format string, v ...interface{}) { + defaultLogger.Printf("[ERROR] "+format, v...) +} + +// Warn ... func Warn(v ...interface{}) { - defaultLogger.Println(os.Stderr, v...) + defaultLogger.Printf("[WARN] %s", fmt.Sprintln(v...)) } -// Warnf . +// Warnf ... func Warnf(format string, v ...interface{}) { - defaultLogger.Printf(os.Stderr, format, v...) + defaultLogger.Printf("[WARN] "+format, v...) } -// Info . +// Info ... func Info(v ...interface{}) { - if Verbose { - defaultLogger.Println(os.Stderr, v...) - } + defaultLogger.Printf("[INFO] %s", fmt.Sprintln(v...)) } -// Infof . +// Infof ... func Infof(format string, v ...interface{}) { - if Verbose { - defaultLogger.Printf(os.Stderr, format, v...) + defaultLogger.Printf("[INFO] "+format, v...) +} + +// Debug ... +func Debug(v ...interface{}) { + if !Verbose { + return + } + defaultLogger.Printf("[DEBUG] %s", fmt.Sprintln(v...)) +} + +// Debugf ... +func Debugf(format string, v ...interface{}) { + if !Verbose { + return } + defaultLogger.Printf("[DEBUG] "+format, v...) } diff --git a/tool/internal_pkg/pluginmode/protoc/plugin.go b/tool/internal_pkg/pluginmode/protoc/plugin.go index a7fb50fc3f..71700645ce 100644 --- a/tool/internal_pkg/pluginmode/protoc/plugin.go +++ b/tool/internal_pkg/pluginmode/protoc/plugin.go @@ -122,11 +122,12 @@ func (pp *protocPlugin) GenerateFile(gen *protogen.Plugin, file *protogen.File) } gopkg := file.Proto.GetOptions().GetGoPackage() if !strings.HasPrefix(gopkg, pp.PackagePrefix) { - log.Warnf("[WARN] %q is skipped because its import path %q is not located in ./kitex_gen. Change the go_package option or use '--protobuf M%s=A-Import-Path-In-kitex_gen' to override it if you want this file to be generated under kitex_gen.\n", + log.Warnf("%q is skipped because its import path %q is not located in ./kitex_gen.\n"+ + "Change the go_package option or use '--protobuf M%s=A-Import-Path-In-kitex_gen' to override it if you want this file to be generated under kitex_gen.\n", file.Proto.GetName(), gopkg, file.Proto.GetName()) return } - log.Infof("[INFO] Generate %q at %q\n", file.Proto.GetName(), gopkg) + log.Debugf("Generate %q at %q\n", file.Proto.GetName(), gopkg) if parts := strings.Split(gopkg, ";"); len(parts) > 1 { gopkg = parts[0] // remove package alias from file path @@ -320,7 +321,7 @@ func (pp *protocPlugin) convertTypes(file *protogen.File) (ss []*generator.Servi mm := make(map[string]*generator.MethodInfo) for _, m := range methods { if _, ok := mm[m.Name]; ok { - log.Warnf("[WARN] combine service method %s in %s conflicts with %s in %s\n", + log.Warnf("combine service method %s in %s conflicts with %s in %s\n", m.Name, m.ServiceName, m.Name, mm[m.Name].ServiceName) return } diff --git a/tool/internal_pkg/pluginmode/protoc/protoc.go b/tool/internal_pkg/pluginmode/protoc/protoc.go index 28c53c4588..8a3e7c6e05 100644 --- a/tool/internal_pkg/pluginmode/protoc/protoc.go +++ b/tool/internal_pkg/pluginmode/protoc/protoc.go @@ -93,7 +93,7 @@ func GenKitex(req *pluginpb.CodeGeneratorRequest, opts protogen.Options) (*plugi gopkg, ok := pp.importPaths[f.GetName()] if ok { f.Options.GoPackage = &gopkg - log.Infof("[INFO] option specified import path for %q: %q\n", f.GetName(), gopkg) + log.Debugf("option specified import path for %q: %q\n", f.GetName(), gopkg) } else { if f.Options == nil || f.Options.GoPackage == nil { return nil, fmt.Errorf("ERROR: go_package is missing in proto file %q", f.GetName()) @@ -102,7 +102,7 @@ func GenKitex(req *pluginpb.CodeGeneratorRequest, opts protogen.Options) (*plugi } if path, ok := pe.getImportPath(gopkg); ok { f.Options.GoPackage = &path - log.Infof("[INFO] update import path for %q: %q -> %q\n", f.GetName(), gopkg, path) + log.Debugf("update import path for %q: %q -> %q\n", f.GetName(), gopkg, path) } } diff --git a/tool/internal_pkg/pluginmode/thriftgo/convertor.go b/tool/internal_pkg/pluginmode/thriftgo/convertor.go index 2137eaaa2d..072d08616f 100644 --- a/tool/internal_pkg/pluginmode/thriftgo/convertor.go +++ b/tool/internal_pkg/pluginmode/thriftgo/convertor.go @@ -17,7 +17,6 @@ package thriftgo import ( "fmt" "go/format" - "io" "os" "path/filepath" "regexp" @@ -31,7 +30,7 @@ import ( "github.com/cloudwego/thriftgo/semantic" "github.com/cloudwego/kitex/tool/internal_pkg/generator" - internal_log "github.com/cloudwego/kitex/tool/internal_pkg/log" + "github.com/cloudwego/kitex/tool/internal_pkg/log" "github.com/cloudwego/kitex/tool/internal_pkg/util" "github.com/cloudwego/kitex/transport" ) @@ -80,20 +79,9 @@ func (c *converter) initLogs() backend.LogFunc { lf.Info = lf.Warn } - internal_log.SetDefaultLogger(internal_log.Logger{ - Println: func(w io.Writer, a ...interface{}) (n int, err error) { - if w != os.Stdout || c.Config.Verbose { - c.Warnings = append(c.Warnings, fmt.Sprint(a...)) - } - return 0, nil - }, - Printf: func(w io.Writer, format string, a ...interface{}) (n int, err error) { - if w != os.Stdout || c.Config.Verbose { - c.Warnings = append(c.Warnings, fmt.Sprintf(format, a...)) - } - return 0, nil - }, - }) + log.SetDefaultLogger(log.LoggerFunc(func(format string, a ...interface{}) { + c.Warnings = append(c.Warnings, fmt.Sprintf(format, a...)) + })) return lf } @@ -516,13 +504,13 @@ func (c *converter) persist(res *plugin.Response) error { content := []byte(c.Content) if filepath.Ext(full) == ".go" { if formatted, err := format.Source([]byte(c.Content)); err != nil { - internal_log.Warn(fmt.Sprintf("Failed to format %s: %s", full, err.Error())) + log.Warnf("Failed to format %s: %s", full, err) } else { content = formatted } } - internal_log.Info("Write", full) + log.Debug("Write", full) path := filepath.Dir(full) if err := os.MkdirAll(path, 0o755); err != nil && !os.IsExist(err) { return fmt.Errorf("failed to create path '%s': %w", path, err)