Skip to content

Commit

Permalink
chore(tool): clearer log pkg usage (#1678)
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaost authored Jan 20, 2025
1 parent 789cc11 commit 1de9e03
Show file tree
Hide file tree
Showing 12 changed files with 93 additions and 73 deletions.
15 changes: 8 additions & 7 deletions tool/cmd/kitex/args/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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!")
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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 {
Expand All @@ -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
}

Expand Down
13 changes: 7 additions & 6 deletions tool/cmd/kitex/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package main

import (
"bytes"
"errors"
"flag"
"os"
"path/filepath"
Expand Down Expand Up @@ -56,7 +57,7 @@ func init() {
Version: "v0.11.0",
},
); err != nil {
log.Warn(err)
log.Error(err)
os.Exit(versions.CompatibilityCheckExitCode)
}
}
Expand All @@ -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
Expand Down
20 changes: 8 additions & 12 deletions tool/cmd/kitex/sdk/kitex_sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package sdk

import (
"bytes"
"errors"
"flag"
"fmt"
"os/exec"
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion tool/cmd/kitex/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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/[email protected]"
Expand Down
2 changes: 1 addition & 1 deletion tool/cmd/kitex/versions/dependencies.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
8 changes: 5 additions & 3 deletions tool/internal_pkg/generator/completor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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"]
Expand Down
2 changes: 1 addition & 1 deletion tool/internal_pkg/generator/custom_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion tool/internal_pkg/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
67 changes: 49 additions & 18 deletions tool/internal_pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,49 +16,80 @@ package log

import (
"fmt"
"io"
"log"
"os"
)

// Verbose decides whether the informatc logs should be output.
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.
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...)
}
7 changes: 4 additions & 3 deletions tool/internal_pkg/pluginmode/protoc/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions tool/internal_pkg/pluginmode/protoc/protoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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)
}
}

Expand Down
Loading

0 comments on commit 1de9e03

Please sign in to comment.