Compare commits

...

2 Commits

Author SHA1 Message Date
fd92fd2409 version updates 2022-03-25 14:13:49 +08:00
a2823a501e upgrade otel to v1.0.0 for compatibility 2022-03-25 11:06:23 +08:00
14 changed files with 144 additions and 138 deletions

View File

@ -8,7 +8,6 @@ package gdebug
import ( import (
"fmt" "fmt"
"github.com/gogf/gf/internal/utils"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -34,7 +33,7 @@ func init() {
goRootForFilter = strings.Replace(goRootForFilter, "\\", "/", -1) goRootForFilter = strings.Replace(goRootForFilter, "\\", "/", -1)
} }
// Initialize internal package variable: selfPath. // Initialize internal package variable: selfPath.
selfPath, _ := exec.LookPath(os.Args[0]) selfPath, _ = exec.LookPath(os.Args[0])
if selfPath != "" { if selfPath != "" {
selfPath, _ = filepath.Abs(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 // Caller returns the function name and the absolute file path along with its line
// number of the caller. // number of the caller.
func Caller(skip ...int) (function string, path string, line int) { 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 // CallerWithFilter returns the function name and the absolute file path along with
// its line number of the caller. // its line number of the caller.
// //
// The parameter `filter` is used to filter the path of the caller. // The parameter `filters` is used to filter the path of the caller.
func CallerWithFilter(filter string, skip ...int) (function string, path string, line int) { func CallerWithFilter(filters []string, skip ...int) (function string, path string, line int) {
var ( var (
number = 0 number = 0
ok = true ok = true
@ -61,14 +60,17 @@ func CallerWithFilter(filter string, skip ...int) (function string, path string,
if len(skip) > 0 { if len(skip) > 0 {
number = skip[0] number = skip[0]
} }
pc, file, line, start := callerFromIndex([]string{filter}) pc, file, line, start := callerFromIndex(filters)
if start != -1 { if start != -1 {
for i := start + number; i < maxCallerDepth; i++ { for i := start + number; i < maxCallerDepth; i++ {
if i != start { if i != start {
pc, file, line, ok = runtime.Caller(i) pc, file, line, ok = runtime.Caller(i)
} }
if ok { if ok {
function := "" if filterFileByFilters(file, filters) {
continue
}
function = ""
if fn := runtime.FuncForPC(pc); fn == nil { if fn := runtime.FuncForPC(pc); fn == nil {
function = "unknown" function = "unknown"
} else { } 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 // callerFromIndex returns the caller position and according information exclusive of the
// debug package. // debug package.
// //
// VERY NOTE THAT, the returned index value should be <index - 1> 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) { 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++ { for index = 0; index < maxCallerDepth; index++ {
if pc, file, line, ok = runtime.Caller(index); ok { if pc, file, line, ok = runtime.Caller(index); ok {
filtered = false if filterFileByFilters(file, filters) {
for _, filter := range filters {
if filter != "" && strings.Contains(file, filter) {
filtered = true
break
}
}
if filtered {
continue continue
} }
if !utils.IsDebugEnabled() {
if strings.Contains(file, utils.StackFilterKeyForGoFrame) {
continue
}
} else {
if strings.Contains(file, stackFilterKey) {
continue
}
}
if index > 0 { if index > 0 {
index-- index--
} }
@ -119,6 +105,27 @@ func callerFromIndex(filters []string) (pc uintptr, file string, line int, index
return 0, "", -1, -1 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. // CallerPackage returns the package name of the caller.
func CallerPackage() string { func CallerPackage() string {
function, _, _ := Caller() function, _, _ := Caller()

View File

@ -9,9 +9,7 @@ package gdebug
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/gogf/gf/internal/utils"
"runtime" "runtime"
"strings"
) )
// PrintStack prints to standard error the stack trace returned by runtime.Stack. // 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. // 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. // It calls runtime.Stack with a large enough buffer to capture the entire trace.
func Stack(skip ...int) string { func Stack(skip ...int) string {
return StackWithFilter("", skip...) return StackWithFilter(nil, skip...)
} }
// StackWithFilter returns a formatted stack trace of the goroutine that calls it. // 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. // 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. // The parameter `filter` is used to filter the path of the caller.
func StackWithFilter(filter string, skip ...int) string { func StackWithFilter(filters []string, skip ...int) string {
return StackWithFilters([]string{filter}, skip...) return StackWithFilters(filters, skip...)
} }
// StackWithFilters returns a formatted stack trace of the goroutine that calls it. // StackWithFilters returns a formatted stack trace of the goroutine that calls it.
@ -50,7 +48,6 @@ func StackWithFilters(filters []string, skip ...int) string {
space = " " space = " "
index = 1 index = 1
buffer = bytes.NewBuffer(nil) buffer = bytes.NewBuffer(nil)
filtered = false
ok = true ok = true
pc, file, line, start = callerFromIndex(filters) pc, file, line, start = callerFromIndex(filters)
) )
@ -59,38 +56,9 @@ func StackWithFilters(filters []string, skip ...int) string {
pc, file, line, ok = runtime.Caller(i) pc, file, line, ok = runtime.Caller(i)
} }
if ok { if ok {
// Filter empty file. if filterFileByFilters(file, filters) {
if file == "" {
continue 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 { if fn := runtime.FuncForPC(pc); fn == nil {
name = "unknown" name = "unknown"
} else { } else {

7
go.mod
View File

@ -10,11 +10,10 @@ require (
github.com/go-sql-driver/mysql v1.6.0 github.com/go-sql-driver/mysql v1.6.0
github.com/gomodule/redigo v1.8.5 github.com/gomodule/redigo v1.8.5
github.com/gorilla/websocket v1.4.2 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 github.com/olekukonko/tablewriter v0.0.5
go.opentelemetry.io/otel v1.0.0-RC2 go.opentelemetry.io/otel v1.0.0
go.opentelemetry.io/otel/oteltest v1.0.0-RC2 go.opentelemetry.io/otel/trace v1.0.0
go.opentelemetry.io/otel/trace v1.0.0-RC2
golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 golang.org/x/net v0.0.0-20210520170846-37e1c6afe023
golang.org/x/text v0.3.6 golang.org/x/text v0.3.6
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b

14
go.sum
View File

@ -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/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 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 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.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0=
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/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 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= 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.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 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 h1:qTTn6x71GVBvoafHK/yaRUmFzI4LcONZD0/kXxl5PHI=
go.opentelemetry.io/otel v1.0.0-RC2/go.mod h1:w1thVQ7qbAy8MHb0IFj8a5Q2QU0l2ksf8u/CN8m3NOM= go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnfmS4cg=
go.opentelemetry.io/otel/oteltest v1.0.0-RC2 h1:xNKqMhlZYkASSyvF4JwObZFMq0jhFN3c3SP+2rCzVPk= go.opentelemetry.io/otel/trace v1.0.0 h1:TSBr8GTEtKevYMG/2d21M989r5WJYVimhTHBKVEZuh4=
go.opentelemetry.io/otel/oteltest v1.0.0-RC2/go.mod h1:kiQ4tw5tAL4JLTbcOYwK1CWI1HkT5aiLzHovgOVnz/A= go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs=
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=
golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 h1:ADo5wSpq2gqaCGQWzk7S5vd//0iyyLeAratkEoG5dLE= 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/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View File

@ -11,11 +11,13 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"github.com/gogf/gf/debug/gdebug"
"github.com/gogf/gf/internal/utils"
"go.opentelemetry.io/otel/trace"
"path/filepath" "path/filepath"
"time" "time"
"go.opentelemetry.io/otel/trace"
"github.com/gogf/gf/debug/gdebug"
"github.com/gogf/gf/internal/utils"
) )
const ( const (
@ -43,23 +45,35 @@ func SetEnabled(enabled bool) {
// Print prints `v` with newline using fmt.Println. // Print prints `v` with newline using fmt.Println.
// The parameter `v` can be multiple variables. // The parameter `v` can be multiple variables.
func Print(ctx context.Context, v ...interface{}) { func Print(ctx context.Context, v ...interface{}) {
if !isGFDebug {
return
}
doPrint(ctx, fmt.Sprint(v...), false) doPrint(ctx, fmt.Sprint(v...), false)
} }
// Printf prints `v` with format `format` using fmt.Printf. // Printf prints `v` with format `format` using fmt.Printf.
// The parameter `v` can be multiple variables. // The parameter `v` can be multiple variables.
func Printf(ctx context.Context, format string, v ...interface{}) { func Printf(ctx context.Context, format string, v ...interface{}) {
if !isGFDebug {
return
}
doPrint(ctx, fmt.Sprintf(format, v...), false) doPrint(ctx, fmt.Sprintf(format, v...), false)
} }
// Error prints `v` with newline using fmt.Println. // Error prints `v` with newline using fmt.Println.
// The parameter `v` can be multiple variables. // The parameter `v` can be multiple variables.
func Error(ctx context.Context, v ...interface{}) { func Error(ctx context.Context, v ...interface{}) {
if !isGFDebug {
return
}
doPrint(ctx, fmt.Sprint(v...), true) doPrint(ctx, fmt.Sprint(v...), true)
} }
// Errorf prints `v` with format `format` using fmt.Printf. // Errorf prints `v` with format `format` using fmt.Printf.
func Errorf(ctx context.Context, format string, v ...interface{}) { func Errorf(ctx context.Context, format string, v ...interface{}) {
if !isGFDebug {
return
}
doPrint(ctx, fmt.Sprintf(format, v...), true) doPrint(ctx, fmt.Sprintf(format, v...), true)
} }
@ -94,7 +108,7 @@ func doPrint(ctx context.Context, content string, stack bool) {
return return
} }
buffer := bytes.NewBuffer(nil) buffer := bytes.NewBuffer(nil)
buffer.WriteString(now()) buffer.WriteString(time.Now().Format("2006-01-02 15:04:05.000"))
buffer.WriteString(" [INTE] ") buffer.WriteString(" [INTE] ")
buffer.WriteString(file()) buffer.WriteString(file())
buffer.WriteString(" ") buffer.WriteString(" ")
@ -104,7 +118,7 @@ func doPrint(ctx context.Context, content string, stack bool) {
buffer.WriteString(content) buffer.WriteString(content)
buffer.WriteString("\n") buffer.WriteString("\n")
if stack { if stack {
buffer.WriteString(gdebug.StackWithFilter(stackFilterKey)) buffer.WriteString(gdebug.StackWithFilter([]string{stackFilterKey}))
} }
fmt.Print(buffer.String()) fmt.Print(buffer.String())
} }
@ -121,13 +135,8 @@ func traceIdStr(ctx context.Context) string {
return "" 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. // file returns caller file name along with its line number.
func file() string { func file() string {
_, p, l := gdebug.CallerWithFilter(stackFilterKey) _, p, l := gdebug.CallerWithFilter([]string{stackFilterKey})
return fmt.Sprintf(`%s:%d`, filepath.Base(p), l) return fmt.Sprintf(`%s:%d`, filepath.Base(p), l)
} }

View File

@ -8,19 +8,21 @@ package ghttp
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http"
"github.com/gogf/gf" "github.com/gogf/gf"
"github.com/gogf/gf/internal/utils" "github.com/gogf/gf/internal/utils"
"github.com/gogf/gf/net/ghttp/internal/client" "github.com/gogf/gf/net/ghttp/internal/client"
"github.com/gogf/gf/net/ghttp/internal/httputil" "github.com/gogf/gf/net/ghttp/internal/httputil"
"github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/net/gtrace"
"github.com/gogf/gf/text/gstr" "github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"io/ioutil"
"net/http"
) )
const ( const (
@ -56,8 +58,8 @@ func MiddlewareServerTracing(r *Request) {
r.Body = utils.NewReadCloser(reqBodyContentBytes, false) r.Body = utils.NewReadCloser(reqBodyContentBytes, false)
span.AddEvent(tracingEventHttpRequest, trace.WithAttributes( span.AddEvent(tracingEventHttpRequest, trace.WithAttributes(
attribute.Any(tracingEventHttpRequestHeaders, httputil.HeaderToMap(r.Header)), attribute.String(tracingEventHttpRequestHeaders, gconv.String(httputil.HeaderToMap(r.Header))),
attribute.Any(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ctx)), attribute.String(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ctx).String()),
attribute.String(tracingEventHttpRequestBody, gstr.StrLimit( attribute.String(tracingEventHttpRequestBody, gstr.StrLimit(
string(reqBodyContentBytes), string(reqBodyContentBytes),
gtrace.MaxContentLogSize(), gtrace.MaxContentLogSize(),
@ -82,7 +84,7 @@ func MiddlewareServerTracing(r *Request) {
) )
span.AddEvent(tracingEventHttpResponse, trace.WithAttributes( 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), attribute.String(tracingEventHttpResponseBody, resBodyContent),
)) ))
return return

View File

@ -8,10 +8,11 @@ package ghttp
import ( import (
"fmt" "fmt"
"strings"
"github.com/gogf/gf/container/gtype" "github.com/gogf/gf/container/gtype"
"github.com/gogf/gf/errors/gcode" "github.com/gogf/gf/errors/gcode"
"github.com/gogf/gf/errors/gerror" "github.com/gogf/gf/errors/gerror"
"strings"
"github.com/gogf/gf/debug/gdebug" "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) { func (s *Server) setHandler(pattern string, handler *handlerItem) {
handler.Id = handlerIdGenerator.Add(1) handler.Id = handlerIdGenerator.Add(1)
if handler.Source == "" { if handler.Source == "" {
_, file, line := gdebug.CallerWithFilter(stackFilterKey) _, file, line := gdebug.CallerWithFilter([]string{stackFilterKey})
handler.Source = fmt.Sprintf(`%s:%d`, file, line) handler.Source = fmt.Sprintf(`%s:%d`, file, line)
} }
domain, method, uri, err := s.parsePattern(pattern) domain, method, uri, err := s.parsePattern(pattern)

View File

@ -8,10 +8,11 @@ package ghttp
import ( import (
"fmt" "fmt"
"github.com/gogf/gf/debug/gdebug"
"reflect" "reflect"
"strings" "strings"
"github.com/gogf/gf/debug/gdebug"
"github.com/gogf/gf/text/gstr" "github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv" "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. // 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 { 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{ preBindItems = append(preBindItems, &preBindItem{
group: g, group: g,
bindType: bindType, bindType: bindType,

View File

@ -8,19 +8,21 @@ package client
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http"
"net/http/httptrace"
"github.com/gogf/gf" "github.com/gogf/gf"
"github.com/gogf/gf/internal/utils" "github.com/gogf/gf/internal/utils"
"github.com/gogf/gf/net/ghttp/internal/httputil" "github.com/gogf/gf/net/ghttp/internal/httputil"
"github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/net/gtrace"
"github.com/gogf/gf/text/gstr" "github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"io/ioutil"
"net/http"
"net/http/httptrace"
) )
const ( const (
@ -70,7 +72,7 @@ func MiddlewareTracing(c *Client, r *http.Request) (response *Response, err erro
response.Body = utils.NewReadCloser(reqBodyContentBytes, false) response.Body = utils.NewReadCloser(reqBodyContentBytes, false)
span.AddEvent(tracingEventHttpResponse, trace.WithAttributes( 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( attribute.String(tracingEventHttpResponseBody, gstr.StrLimit(
string(reqBodyContentBytes), string(reqBodyContentBytes),
gtrace.MaxContentLogSize(), gtrace.MaxContentLogSize(),

View File

@ -10,18 +10,20 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "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" "io/ioutil"
"net/http" "net/http"
"net/http/httptrace" "net/http/httptrace"
"net/textproto" "net/textproto"
"strings" "strings"
"sync" "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 { type clientTracer struct {
@ -147,8 +149,8 @@ func (ct *clientTracer) wroteRequest(info httptrace.WroteRequestInfo) {
} }
ct.span.AddEvent(tracingEventHttpRequest, trace.WithAttributes( ct.span.AddEvent(tracingEventHttpRequest, trace.WithAttributes(
attribute.Any(tracingEventHttpRequestHeaders, ct.headers), attribute.String(tracingEventHttpRequestHeaders, gconv.String(ct.headers)),
attribute.Any(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ct.Context)), attribute.String(tracingEventHttpRequestBaggage, gtrace.GetBaggageMap(ct.Context).String()),
attribute.String(tracingEventHttpRequestBody, gstr.StrLimit( attribute.String(tracingEventHttpRequestBody, gstr.StrLimit(
string(ct.requestBody), string(ct.requestBody),
gtrace.MaxContentLogSize(), gtrace.MaxContentLogSize(),

View File

@ -8,12 +8,13 @@ package gtrace_test
import ( import (
"context" "context"
"testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"github.com/gogf/gf/net/gtrace" "github.com/gogf/gf/net/gtrace"
"github.com/gogf/gf/test/gtest" "github.com/gogf/gf/test/gtest"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/oteltest"
"go.opentelemetry.io/otel/trace"
"testing"
) )
const ( const (
@ -51,14 +52,17 @@ func TestNewCarrier(t *testing.T) {
SpanID: spanID, SpanID: spanID,
TraceFlags: trace.FlagsSampled, 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() carrier1 := gtrace.NewCarrier()
otel.GetTextMapPropagator().Inject(ctx, carrier1) otel.GetTextMapPropagator().Inject(ctx, carrier1)
t.Assert(carrier1.String(), `{"traceparent":"00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-01"}`)
ctx = otel.GetTextMapPropagator().Extract(ctx, carrier1) ctx = otel.GetTextMapPropagator().Extract(ctx, carrier1)
gotSc := trace.SpanContextFromContext(ctx) gotSc := trace.SpanContextFromContext(ctx)
t.Assert(gotSc.TraceID().String(), traceID.String()) t.Assert(gotSc.TraceID().String(), traceID.String())
t.Assert(gotSc.SpanID().String(), "0000000000000002") // New span is created internally, so the SpanID is different.
}) })
} }

View File

@ -10,6 +10,11 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io"
"os"
"strings"
"time"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/gogf/gf/container/gtype" "github.com/gogf/gf/container/gtype"
"github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/internal/intlog"
@ -18,10 +23,6 @@ import (
"github.com/gogf/gf/os/gmlock" "github.com/gogf/gf/os/gmlock"
"github.com/gogf/gf/os/gtimer" "github.com/gogf/gf/os/gtimer"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"io"
"os"
"strings"
"time"
"github.com/gogf/gf/debug/gdebug" "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. // Caller path and Fn name.
if l.config.Flags&(F_FILE_LONG|F_FILE_SHORT|F_CALLER_FN) > 0 { 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 l.config.Flags&F_CALLER_FN > 0 {
if len(callerFnName) > 2 { if len(callerFnName) > 2 {
input.CallerFunc = fmt.Sprintf(`[%s]`, callerFnName) input.CallerFunc = fmt.Sprintf(`[%s]`, callerFnName)

View File

@ -8,13 +8,14 @@ package gtest
import ( import (
"fmt" "fmt"
"github.com/gogf/gf/internal/empty" "io/ioutil"
"os" "os"
"path/filepath"
"reflect" "reflect"
"testing" "testing"
"github.com/gogf/gf/debug/gdebug" "github.com/gogf/gf/debug/gdebug"
"github.com/gogf/gf/internal/empty"
"github.com/gogf/gf/util/gconv" "github.com/gogf/gf/util/gconv"
) )
@ -22,33 +23,19 @@ const (
pathFilterKey = "/test/gtest/gtest" 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 `t` is the pointer to testing.T of stdlib (*testing.T).
// The parameter `f` is the closure function for unit testing case. // The parameter `f` is the closure function for unit testing case.
func C(t *testing.T, f func(t *T)) { func C(t *testing.T, f func(t *T)) {
defer func() { defer func() {
if err := recover(); err != nil { 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() t.Fail()
} }
}() }()
f(&T{t}) 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. // Assert checks `value` and `expect` EQUAL.
func Assert(value, expect interface{}) { func Assert(value, expect interface{}) {
rvExpect := reflect.ValueOf(expect) rvExpect := reflect.ValueOf(expect)
@ -302,7 +289,7 @@ func Error(message ...interface{}) {
// Fatal prints `message` to stderr and exit the process. // Fatal prints `message` to stderr and exit the process.
func Fatal(message ...interface{}) { 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) os.Exit(1)
} }
@ -357,3 +344,28 @@ func AssertNil(value interface{}) {
} }
AssertNE(value, nil) 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 ""
}

View File

@ -1,4 +1,4 @@
package gf package gf
const VERSION = "v1.16.6" const VERSION = "v1.16.7"
const AUTHORS = "john<john@goframe.org>" const AUTHORS = "john<john@goframe.org>"