diff --git a/debug/gdebug/gdebug_caller.go b/debug/gdebug/gdebug_caller.go index b2e2577f3..5f145502e 100644 --- a/debug/gdebug/gdebug_caller.go +++ b/debug/gdebug/gdebug_caller.go @@ -8,7 +8,6 @@ package gdebug import ( "fmt" - "github.com/gogf/gf/internal/utils" "os" "os/exec" "path/filepath" @@ -34,7 +33,7 @@ func init() { goRootForFilter = strings.Replace(goRootForFilter, "\\", "/", -1) } // Initialize internal package variable: selfPath. - selfPath, _ := exec.LookPath(os.Args[0]) + selfPath, _ = exec.LookPath(os.Args[0]) if selfPath != "" { selfPath, _ = filepath.Abs(selfPath) } @@ -46,14 +45,14 @@ func init() { // Caller returns the function name and the absolute file path along with its line // number of the caller. func Caller(skip ...int) (function string, path string, line int) { - return CallerWithFilter("", skip...) + return CallerWithFilter(nil, skip...) } // CallerWithFilter returns the function name and the absolute file path along with // its line number of the caller. // -// The parameter `filter` is used to filter the path of the caller. -func CallerWithFilter(filter string, skip ...int) (function string, path string, line int) { +// The parameter `filters` is used to filter the path of the caller. +func CallerWithFilter(filters []string, skip ...int) (function string, path string, line int) { var ( number = 0 ok = true @@ -61,14 +60,17 @@ func CallerWithFilter(filter string, skip ...int) (function string, path string, if len(skip) > 0 { number = skip[0] } - pc, file, line, start := callerFromIndex([]string{filter}) + pc, file, line, start := callerFromIndex(filters) if start != -1 { for i := start + number; i < maxCallerDepth; i++ { if i != start { pc, file, line, ok = runtime.Caller(i) } if ok { - function := "" + if filterFileByFilters(file, filters) { + continue + } + function = "" if fn := runtime.FuncForPC(pc); fn == nil { function = "unknown" } else { @@ -86,30 +88,14 @@ func CallerWithFilter(filter string, skip ...int) (function string, path string, // callerFromIndex returns the caller position and according information exclusive of the // debug package. // -// VERY NOTE THAT, the returned index value should be as the caller's start point. +// VERY NOTE THAT, the returned index value should be `index - 1` as the caller's start point. func callerFromIndex(filters []string) (pc uintptr, file string, line int, index int) { - var filtered, ok bool + var ok bool for index = 0; index < maxCallerDepth; index++ { if pc, file, line, ok = runtime.Caller(index); ok { - filtered = false - for _, filter := range filters { - if filter != "" && strings.Contains(file, filter) { - filtered = true - break - } - } - if filtered { + if filterFileByFilters(file, filters) { continue } - if !utils.IsDebugEnabled() { - if strings.Contains(file, utils.StackFilterKeyForGoFrame) { - continue - } - } else { - if strings.Contains(file, stackFilterKey) { - continue - } - } if index > 0 { index-- } @@ -119,6 +105,27 @@ func callerFromIndex(filters []string) (pc uintptr, file string, line int, index return 0, "", -1, -1 } +func filterFileByFilters(file string, filters []string) (filtered bool) { + // Filter empty file. + if file == "" { + return true + } + // Filter gdebug package callings. + if strings.Contains(file, stackFilterKey) { + return true + } + for _, filter := range filters { + if filter != "" && strings.Contains(file, filter) { + return true + } + } + // GOROOT filter. + if goRootForFilter != "" && len(file) >= len(goRootForFilter) && file[0:len(goRootForFilter)] == goRootForFilter { + return true + } + return false +} + // CallerPackage returns the package name of the caller. func CallerPackage() string { function, _, _ := Caller() diff --git a/debug/gdebug/gdebug_stack.go b/debug/gdebug/gdebug_stack.go index 1a2f0c37d..0bfc6030c 100644 --- a/debug/gdebug/gdebug_stack.go +++ b/debug/gdebug/gdebug_stack.go @@ -9,9 +9,7 @@ package gdebug import ( "bytes" "fmt" - "github.com/gogf/gf/internal/utils" "runtime" - "strings" ) // PrintStack prints to standard error the stack trace returned by runtime.Stack. @@ -22,15 +20,15 @@ func PrintStack(skip ...int) { // Stack returns a formatted stack trace of the goroutine that calls it. // It calls runtime.Stack with a large enough buffer to capture the entire trace. func Stack(skip ...int) string { - return StackWithFilter("", skip...) + return StackWithFilter(nil, skip...) } // StackWithFilter returns a formatted stack trace of the goroutine that calls it. // It calls runtime.Stack with a large enough buffer to capture the entire trace. // // The parameter `filter` is used to filter the path of the caller. -func StackWithFilter(filter string, skip ...int) string { - return StackWithFilters([]string{filter}, skip...) +func StackWithFilter(filters []string, skip ...int) string { + return StackWithFilters(filters, skip...) } // StackWithFilters returns a formatted stack trace of the goroutine that calls it. @@ -50,7 +48,6 @@ func StackWithFilters(filters []string, skip ...int) string { space = " " index = 1 buffer = bytes.NewBuffer(nil) - filtered = false ok = true pc, file, line, start = callerFromIndex(filters) ) @@ -59,38 +56,9 @@ func StackWithFilters(filters []string, skip ...int) string { pc, file, line, ok = runtime.Caller(i) } if ok { - // Filter empty file. - if file == "" { + if filterFileByFilters(file, filters) { continue } - // GOROOT filter. - if goRootForFilter != "" && - len(file) >= len(goRootForFilter) && - file[0:len(goRootForFilter)] == goRootForFilter { - continue - } - // Custom filtering. - filtered = false - for _, filter := range filters { - if filter != "" && strings.Contains(file, filter) { - filtered = true - break - } - } - if filtered { - continue - } - - if !utils.IsDebugEnabled() { - if strings.Contains(file, utils.StackFilterKeyForGoFrame) { - continue - } - } else { - if strings.Contains(file, stackFilterKey) { - continue - } - } - if fn := runtime.FuncForPC(pc); fn == nil { name = "unknown" } else { diff --git a/go.mod b/go.mod index bbdb48b3a..146f1e6fa 100644 --- a/go.mod +++ b/go.mod @@ -10,11 +10,10 @@ require ( github.com/go-sql-driver/mysql v1.6.0 github.com/gomodule/redigo v1.8.5 github.com/gorilla/websocket v1.4.2 - github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf + github.com/grokify/html-strip-tags-go v0.0.1 github.com/olekukonko/tablewriter v0.0.5 - go.opentelemetry.io/otel v1.0.0-RC2 - go.opentelemetry.io/otel/oteltest v1.0.0-RC2 - go.opentelemetry.io/otel/trace v1.0.0-RC2 + go.opentelemetry.io/otel v1.0.0 + go.opentelemetry.io/otel/trace v1.0.0 golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 golang.org/x/text v0.3.6 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b diff --git a/go.sum b/go.sum index 72133957f..c5fa667e1 100644 --- a/go.sum +++ b/go.sum @@ -16,8 +16,8 @@ github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf h1:wIOAyJMMen0ELGiFzlmqxdcV1yGbkyHBAB6PolcNbLA= -github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= +github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0= +github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= @@ -32,12 +32,10 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -go.opentelemetry.io/otel v1.0.0-RC2 h1:SHhxSjB+omnGZPgGlKe+QMp3MyazcOHdQ8qwo89oKbg= -go.opentelemetry.io/otel v1.0.0-RC2/go.mod h1:w1thVQ7qbAy8MHb0IFj8a5Q2QU0l2ksf8u/CN8m3NOM= -go.opentelemetry.io/otel/oteltest v1.0.0-RC2 h1:xNKqMhlZYkASSyvF4JwObZFMq0jhFN3c3SP+2rCzVPk= -go.opentelemetry.io/otel/oteltest v1.0.0-RC2/go.mod h1:kiQ4tw5tAL4JLTbcOYwK1CWI1HkT5aiLzHovgOVnz/A= -go.opentelemetry.io/otel/trace v1.0.0-RC2 h1:dunAP0qDULMIT82atj34m5RgvsIK6LcsXf1c/MsYg1w= -go.opentelemetry.io/otel/trace v1.0.0-RC2/go.mod h1:JPQ+z6nNw9mqEGT8o3eoPTdnNI+Aj5JcxEsVGREIAy4= +go.opentelemetry.io/otel v1.0.0 h1:qTTn6x71GVBvoafHK/yaRUmFzI4LcONZD0/kXxl5PHI= +go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnfmS4cg= +go.opentelemetry.io/otel/trace v1.0.0 h1:TSBr8GTEtKevYMG/2d21M989r5WJYVimhTHBKVEZuh4= +go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/internal/intlog/intlog.go b/internal/intlog/intlog.go index f5f3559c9..65438911d 100644 --- a/internal/intlog/intlog.go +++ b/internal/intlog/intlog.go @@ -11,11 +11,13 @@ import ( "bytes" "context" "fmt" - "github.com/gogf/gf/debug/gdebug" - "github.com/gogf/gf/internal/utils" - "go.opentelemetry.io/otel/trace" "path/filepath" "time" + + "go.opentelemetry.io/otel/trace" + + "github.com/gogf/gf/debug/gdebug" + "github.com/gogf/gf/internal/utils" ) const ( @@ -43,23 +45,35 @@ func SetEnabled(enabled bool) { // Print prints `v` with newline using fmt.Println. // The parameter `v` can be multiple variables. func Print(ctx context.Context, v ...interface{}) { + if !isGFDebug { + return + } doPrint(ctx, fmt.Sprint(v...), false) } // Printf prints `v` with format `format` using fmt.Printf. // The parameter `v` can be multiple variables. func Printf(ctx context.Context, format string, v ...interface{}) { + if !isGFDebug { + return + } doPrint(ctx, fmt.Sprintf(format, v...), false) } // Error prints `v` with newline using fmt.Println. // The parameter `v` can be multiple variables. func Error(ctx context.Context, v ...interface{}) { + if !isGFDebug { + return + } doPrint(ctx, fmt.Sprint(v...), true) } // Errorf prints `v` with format `format` using fmt.Printf. func Errorf(ctx context.Context, format string, v ...interface{}) { + if !isGFDebug { + return + } doPrint(ctx, fmt.Sprintf(format, v...), true) } @@ -94,7 +108,7 @@ func doPrint(ctx context.Context, content string, stack bool) { return } buffer := bytes.NewBuffer(nil) - buffer.WriteString(now()) + buffer.WriteString(time.Now().Format("2006-01-02 15:04:05.000")) buffer.WriteString(" [INTE] ") buffer.WriteString(file()) buffer.WriteString(" ") @@ -104,7 +118,7 @@ func doPrint(ctx context.Context, content string, stack bool) { buffer.WriteString(content) buffer.WriteString("\n") if stack { - buffer.WriteString(gdebug.StackWithFilter(stackFilterKey)) + buffer.WriteString(gdebug.StackWithFilter([]string{stackFilterKey})) } fmt.Print(buffer.String()) } @@ -121,13 +135,8 @@ func traceIdStr(ctx context.Context) string { return "" } -// now returns current time string. -func now() string { - return time.Now().Format("2006-01-02 15:04:05.000") -} - // file returns caller file name along with its line number. func file() string { - _, p, l := gdebug.CallerWithFilter(stackFilterKey) + _, p, l := gdebug.CallerWithFilter([]string{stackFilterKey}) return fmt.Sprintf(`%s:%d`, filepath.Base(p), l) } diff --git a/net/ghttp/ghttp_middleware_tracing.go b/net/ghttp/ghttp_middleware_tracing.go index 052b4ee7e..aa28222ad 100644 --- a/net/ghttp/ghttp_middleware_tracing.go +++ b/net/ghttp/ghttp_middleware_tracing.go @@ -8,19 +8,21 @@ package ghttp import ( "fmt" + "io/ioutil" + "net/http" + "github.com/gogf/gf" "github.com/gogf/gf/internal/utils" "github.com/gogf/gf/net/ghttp/internal/client" "github.com/gogf/gf/net/ghttp/internal/httputil" "github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/text/gstr" + "github.com/gogf/gf/util/gconv" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" - "io/ioutil" - "net/http" ) const ( @@ -56,8 +58,8 @@ func MiddlewareServerTracing(r *Request) { r.Body = utils.NewReadCloser(reqBodyContentBytes, false) span.AddEvent(tracingEventHttpRequest, trace.WithAttributes( - attribute.Any(tracingEventHttpRequestHeaders, httputil.HeaderToMap(r.Header)), - attribute.Any(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ctx)), + attribute.String(tracingEventHttpRequestHeaders, gconv.String(httputil.HeaderToMap(r.Header))), + attribute.String(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ctx).String()), attribute.String(tracingEventHttpRequestBody, gstr.StrLimit( string(reqBodyContentBytes), gtrace.MaxContentLogSize(), @@ -82,7 +84,7 @@ func MiddlewareServerTracing(r *Request) { ) span.AddEvent(tracingEventHttpResponse, trace.WithAttributes( - attribute.Any(tracingEventHttpResponseHeaders, httputil.HeaderToMap(r.Response.Header())), + attribute.String(tracingEventHttpResponseHeaders, gconv.String(httputil.HeaderToMap(r.Response.Header()))), attribute.String(tracingEventHttpResponseBody, resBodyContent), )) return diff --git a/net/ghttp/ghttp_server_router.go b/net/ghttp/ghttp_server_router.go index 83d061b5e..8f9145950 100644 --- a/net/ghttp/ghttp_server_router.go +++ b/net/ghttp/ghttp_server_router.go @@ -8,10 +8,11 @@ package ghttp import ( "fmt" + "strings" + "github.com/gogf/gf/container/gtype" "github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gerror" - "strings" "github.com/gogf/gf/debug/gdebug" @@ -69,7 +70,7 @@ func (s *Server) parsePattern(pattern string) (domain, method, path string, err func (s *Server) setHandler(pattern string, handler *handlerItem) { handler.Id = handlerIdGenerator.Add(1) if handler.Source == "" { - _, file, line := gdebug.CallerWithFilter(stackFilterKey) + _, file, line := gdebug.CallerWithFilter([]string{stackFilterKey}) handler.Source = fmt.Sprintf(`%s:%d`, file, line) } domain, method, uri, err := s.parsePattern(pattern) diff --git a/net/ghttp/ghttp_server_router_group.go b/net/ghttp/ghttp_server_router_group.go index 1eaf85b3a..173c20e54 100644 --- a/net/ghttp/ghttp_server_router_group.go +++ b/net/ghttp/ghttp_server_router_group.go @@ -8,10 +8,11 @@ package ghttp import ( "fmt" - "github.com/gogf/gf/debug/gdebug" "reflect" "strings" + "github.com/gogf/gf/debug/gdebug" + "github.com/gogf/gf/text/gstr" "github.com/gogf/gf/util/gconv" @@ -264,7 +265,7 @@ func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup { // preBindToLocalArray adds the route registering parameters to internal variable array for lazily registering feature. func (g *RouterGroup) preBindToLocalArray(bindType string, pattern string, object interface{}, params ...interface{}) *RouterGroup { - _, file, line := gdebug.CallerWithFilter(stackFilterKey) + _, file, line := gdebug.CallerWithFilter([]string{stackFilterKey}) preBindItems = append(preBindItems, &preBindItem{ group: g, bindType: bindType, diff --git a/net/ghttp/internal/client/client_tracing.go b/net/ghttp/internal/client/client_tracing.go index 567ea6c14..138a71966 100644 --- a/net/ghttp/internal/client/client_tracing.go +++ b/net/ghttp/internal/client/client_tracing.go @@ -8,19 +8,21 @@ package client import ( "fmt" + "io/ioutil" + "net/http" + "net/http/httptrace" + "github.com/gogf/gf" "github.com/gogf/gf/internal/utils" "github.com/gogf/gf/net/ghttp/internal/httputil" "github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/text/gstr" + "github.com/gogf/gf/util/gconv" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" - "io/ioutil" - "net/http" - "net/http/httptrace" ) const ( @@ -70,7 +72,7 @@ func MiddlewareTracing(c *Client, r *http.Request) (response *Response, err erro response.Body = utils.NewReadCloser(reqBodyContentBytes, false) span.AddEvent(tracingEventHttpResponse, trace.WithAttributes( - attribute.Any(tracingEventHttpResponseHeaders, httputil.HeaderToMap(response.Header)), + attribute.String(tracingEventHttpResponseHeaders, gconv.String(httputil.HeaderToMap(response.Header))), attribute.String(tracingEventHttpResponseBody, gstr.StrLimit( string(reqBodyContentBytes), gtrace.MaxContentLogSize(), diff --git a/net/ghttp/internal/client/client_tracing_tracer.go b/net/ghttp/internal/client/client_tracing_tracer.go index ef4733f45..4cfcfd27b 100644 --- a/net/ghttp/internal/client/client_tracing_tracer.go +++ b/net/ghttp/internal/client/client_tracing_tracer.go @@ -10,18 +10,20 @@ import ( "context" "crypto/tls" "fmt" - "github.com/gogf/gf/internal/utils" - "github.com/gogf/gf/net/gtrace" - "github.com/gogf/gf/text/gstr" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/trace" "io/ioutil" "net/http" "net/http/httptrace" "net/textproto" "strings" "sync" + + "github.com/gogf/gf/internal/utils" + "github.com/gogf/gf/net/gtrace" + "github.com/gogf/gf/text/gstr" + "github.com/gogf/gf/util/gconv" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" ) type clientTracer struct { @@ -147,8 +149,8 @@ func (ct *clientTracer) wroteRequest(info httptrace.WroteRequestInfo) { } ct.span.AddEvent(tracingEventHttpRequest, trace.WithAttributes( - attribute.Any(tracingEventHttpRequestHeaders, ct.headers), - attribute.Any(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ct.Context)), + attribute.String(tracingEventHttpRequestHeaders, gconv.String(ct.headers)), + attribute.String(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ct.Context).String()), attribute.String(tracingEventHttpRequestBody, gstr.StrLimit( string(ct.requestBody), gtrace.MaxContentLogSize(), diff --git a/net/gtrace/gtrace_unit_carrier_test.go b/net/gtrace/gtrace_unit_carrier_test.go index 095250c92..f4c831345 100644 --- a/net/gtrace/gtrace_unit_carrier_test.go +++ b/net/gtrace/gtrace_unit_carrier_test.go @@ -8,12 +8,13 @@ package gtrace_test import ( "context" + "testing" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" + "github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/test/gtest" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/oteltest" - "go.opentelemetry.io/otel/trace" - "testing" ) const ( @@ -51,14 +52,17 @@ func TestNewCarrier(t *testing.T) { SpanID: spanID, TraceFlags: trace.FlagsSampled, })) - ctx, _ = oteltest.DefaultTracer().Start(ctx, "inject") + sc := trace.SpanContextFromContext(ctx) + t.Assert(sc.TraceID().String(), traceID.String()) + t.Assert(sc.SpanID().String(), "00f067aa0ba902b7") + + ctx, _ = otel.Tracer("").Start(ctx, "inject") carrier1 := gtrace.NewCarrier() otel.GetTextMapPropagator().Inject(ctx, carrier1) - t.Assert(carrier1.String(), `{"traceparent":"00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-01"}`) ctx = otel.GetTextMapPropagator().Extract(ctx, carrier1) gotSc := trace.SpanContextFromContext(ctx) t.Assert(gotSc.TraceID().String(), traceID.String()) - t.Assert(gotSc.SpanID().String(), "0000000000000002") + // New span is created internally, so the SpanID is different. }) } diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index b52b860b1..213767a93 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -10,6 +10,11 @@ import ( "bytes" "context" "fmt" + "io" + "os" + "strings" + "time" + "github.com/fatih/color" "github.com/gogf/gf/container/gtype" "github.com/gogf/gf/internal/intlog" @@ -18,10 +23,6 @@ import ( "github.com/gogf/gf/os/gmlock" "github.com/gogf/gf/os/gtimer" "go.opentelemetry.io/otel/trace" - "io" - "os" - "strings" - "time" "github.com/gogf/gf/debug/gdebug" @@ -152,7 +153,7 @@ func (l *Logger) print(ctx context.Context, level int, values ...interface{}) { // Caller path and Fn name. if l.config.Flags&(F_FILE_LONG|F_FILE_SHORT|F_CALLER_FN) > 0 { - callerFnName, path, line := gdebug.CallerWithFilter(pathFilterKey, l.config.StSkip) + callerFnName, path, line := gdebug.CallerWithFilter([]string{pathFilterKey}, l.config.StSkip) if l.config.Flags&F_CALLER_FN > 0 { if len(callerFnName) > 2 { input.CallerFunc = fmt.Sprintf(`[%s]`, callerFnName) diff --git a/test/gtest/gtest_util.go b/test/gtest/gtest_util.go index a1644afa2..8f4077e03 100644 --- a/test/gtest/gtest_util.go +++ b/test/gtest/gtest_util.go @@ -8,13 +8,14 @@ package gtest import ( "fmt" - "github.com/gogf/gf/internal/empty" + "io/ioutil" "os" + "path/filepath" "reflect" "testing" "github.com/gogf/gf/debug/gdebug" - + "github.com/gogf/gf/internal/empty" "github.com/gogf/gf/util/gconv" ) @@ -22,33 +23,19 @@ const ( pathFilterKey = "/test/gtest/gtest" ) -// C creates an unit testing case. +// C creates a unit testing case. // The parameter `t` is the pointer to testing.T of stdlib (*testing.T). // The parameter `f` is the closure function for unit testing case. func C(t *testing.T, f func(t *T)) { defer func() { if err := recover(); err != nil { - fmt.Fprintf(os.Stderr, "%v\n%s", err, gdebug.StackWithFilter(pathFilterKey)) + _, _ = fmt.Fprintf(os.Stderr, "%v\n%s", err, gdebug.StackWithFilter([]string{pathFilterKey})) t.Fail() } }() f(&T{t}) } -// Case creates an unit testing case. -// The parameter `t` is the pointer to testing.T of stdlib (*testing.T). -// The parameter `f` is the closure function for unit testing case. -// Deprecated. -func Case(t *testing.T, f func()) { - defer func() { - if err := recover(); err != nil { - fmt.Fprintf(os.Stderr, "%v\n%s", err, gdebug.StackWithFilter(pathFilterKey)) - t.Fail() - } - }() - f() -} - // Assert checks `value` and `expect` EQUAL. func Assert(value, expect interface{}) { rvExpect := reflect.ValueOf(expect) @@ -302,7 +289,7 @@ func Error(message ...interface{}) { // Fatal prints `message` to stderr and exit the process. func Fatal(message ...interface{}) { - fmt.Fprintf(os.Stderr, "[FATAL] %s\n%s", fmt.Sprint(message...), gdebug.StackWithFilter(pathFilterKey)) + fmt.Fprintf(os.Stderr, "[FATAL] %s\n%s", fmt.Sprint(message...), gdebug.StackWithFilter([]string{pathFilterKey})) os.Exit(1) } @@ -357,3 +344,28 @@ func AssertNil(value interface{}) { } AssertNE(value, nil) } + +// DataPath retrieves and returns the testdata path of current package, +// which is used for unit testing cases only. +// The optional parameter `names` specifies the sub-folders/sub-files, +// which will be joined with current system separator and returned with the path. +func DataPath(names ...string) string { + _, path, _ := gdebug.CallerWithFilter([]string{pathFilterKey}) + path = filepath.Dir(path) + string(filepath.Separator) + "testdata" + for _, name := range names { + path += string(filepath.Separator) + name + } + return path +} + +// DataContent retrieves and returns the file content for specified testdata path of current package +func DataContent(names ...string) string { + path := DataPath(names...) + if path != "" { + data, err := ioutil.ReadFile(path) + if err == nil { + return string(data) + } + } + return "" +}