From b2b204478620162417730d3eda70d86059e00dfd Mon Sep 17 00:00:00 2001 From: John Guo Date: Fri, 17 Jun 2022 17:41:10 +0800 Subject: [PATCH] add tracing logging content if trace id is available in context for package gcmd --- os/gcmd/gcmd_command_help.go | 9 ++++++++- os/gcmd/gcmd_command_run.go | 17 ++++++++++++----- os/glog/glog.go | 5 +++-- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/os/gcmd/gcmd_command_help.go b/os/gcmd/gcmd_command_help.go index 7f9ff472a..ab43641e9 100644 --- a/os/gcmd/gcmd_command_help.go +++ b/os/gcmd/gcmd_command_help.go @@ -11,12 +11,19 @@ import ( "bytes" "context" "fmt" + "io" + "os" "github.com/gogf/gf/v2/text/gstr" ) // Print prints help info to stdout for current command. func (c *Command) Print() { + c.PrintTo(os.Stdout) +} + +// PrintTo prints help info to custom io.Writer. +func (c *Command) PrintTo(writer io.Writer) { var ( prefix = gstr.Repeat(" ", 4) buffer = bytes.NewBuffer(nil) @@ -191,7 +198,7 @@ func (c *Command) Print() { } content := buffer.String() content = gstr.Replace(content, "\t", " ") - fmt.Println(content) + _, _ = writer.Write([]byte(content)) } type printLineBriefInput struct { diff --git a/os/gcmd/gcmd_command_run.go b/os/gcmd/gcmd_command_run.go index e9c7111fe..a001009b4 100644 --- a/os/gcmd/gcmd_command_run.go +++ b/os/gcmd/gcmd_command_run.go @@ -8,6 +8,7 @@ package gcmd import ( + "bytes" "context" "fmt" "os" @@ -18,6 +19,7 @@ import ( "github.com/gogf/gf/v2/net/gtrace" "github.com/gogf/gf/v2/os/gcfg" "github.com/gogf/gf/v2/os/genv" + "github.com/gogf/gf/v2/os/glog" "github.com/gogf/gf/v2/text/gstr" "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gutil" @@ -40,18 +42,23 @@ func (c *Command) RunWithValue(ctx context.Context) (value interface{}) { var ( code = gerror.Code(err) detail = code.Detail() + buffer = bytes.NewBuffer(nil) ) if code.Code() == gcode.CodeNotFound.Code() { - fmt.Printf("ERROR: %s\n", gstr.Trim(err.Error())) + buffer.WriteString(fmt.Sprintf("ERROR: %s\n", gstr.Trim(err.Error()))) if lastCmd, ok := detail.(*Command); ok { - lastCmd.Print() + lastCmd.PrintTo(buffer) } else { - c.Print() + c.PrintTo(buffer) } } else { - fmt.Printf("%+v\n", err) + buffer.WriteString(fmt.Sprintf("%+v\n", err)) } - os.Exit(1) + if gtrace.GetTraceID(ctx) == "" { + fmt.Println(buffer.String()) + os.Exit(1) + } + glog.Fatal(ctx, buffer.String()) } return value } diff --git a/os/glog/glog.go b/os/glog/glog.go index fae74aff6..15c9a6576 100644 --- a/os/glog/glog.go +++ b/os/glog/glog.go @@ -8,8 +8,9 @@ package glog import ( - "github.com/gogf/gf/v2/os/gcmd" + "github.com/gogf/gf/v2/internal/command" "github.com/gogf/gf/v2/os/grpool" + "github.com/gogf/gf/v2/util/gconv" ) const ( @@ -30,7 +31,7 @@ var ( ) func init() { - defaultDebug = gcmd.GetOptWithEnv(commandEnvKeyForDebug, true).Bool() + defaultDebug = gconv.Bool(command.GetOptWithEnv(commandEnvKeyForDebug, "true")) SetDebug(defaultDebug) }