Adding support for custom formatter and showing the tracked object pointer

This commit is contained in:
Pavel Shevaev 2022-10-20 12:05:05 +03:00
parent cbd23c5903
commit 9210671236
1 changed files with 8 additions and 4 deletions

View File

@ -22,6 +22,7 @@ const FULL = 2
var mode int32 = OFF var mode int32 = OFF
var res2track = &sync.Map{} var res2track = &sync.Map{}
var customFormatter = func(item *TrackReportItem) string { return "," }
type TrackedInfo struct { type TrackedInfo struct {
Time time.Time Time time.Time
@ -29,7 +30,7 @@ type TrackedInfo struct {
} }
type TrackReportItem struct { type TrackReportItem struct {
T reflect.Type Obj interface{}
Duration time.Duration Duration time.Duration
Stack string Stack string
} }
@ -42,6 +43,10 @@ func InitHandlers() {
http.HandleFunc("/res_tracker/status", statusHandler) http.HandleFunc("/res_tracker/status", statusHandler)
} }
func SetCustomFormatter(f func(item *TrackReportItem) string) {
customFormatter = f
}
func onHandler(w http.ResponseWriter, r *http.Request) { func onHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query() query := r.URL.Query()
m := query.Get("m") m := query.Get("m")
@ -135,7 +140,6 @@ func FormatReportItems() []TrackReportItem {
k := snapshot[i] k := snapshot[i]
v := snapshot[i+1] v := snapshot[i+1]
t := reflect.TypeOf(k)
info, _ := v.(TrackedInfo) info, _ := v.(TrackedInfo)
stackStr := string(info.Stack) stackStr := string(info.Stack)
@ -160,7 +164,7 @@ func FormatReportItems() []TrackReportItem {
} }
} }
items = append(items, TrackReportItem{T: t, Duration: time.Now().Sub(info.Time), Stack: stackStr}) items = append(items, TrackReportItem{Obj: k, Duration: time.Now().Sub(info.Time), Stack: stackStr})
} }
//3. let's sort items by duration descending //3. let's sort items by duration descending
@ -181,7 +185,7 @@ func ReportLines() []string {
lines = append(lines, fmt.Sprintf("=== Tracked connections report %s (total: %d) ===", now.Format("01-02-2006 15:04:05"), len(items))) lines = append(lines, fmt.Sprintf("=== Tracked connections report %s (total: %d) ===", now.Format("01-02-2006 15:04:05"), len(items)))
for idx, item := range items { for idx, item := range items {
//TODO: obtain somehow an actual pointer of the object or provide a hook for a custom formatter //TODO: obtain somehow an actual pointer of the object or provide a hook for a custom formatter
lines = append(lines, fmt.Sprintf("#%d Tracked (%v, duration %v) : %s", idx+1, item.T, item.Duration, item.Stack)) lines = append(lines, fmt.Sprintf("#%d Tracked (%v %p%s duration %v) : %s", idx+1, reflect.TypeOf(item.Obj), item.Obj, customFormatter(&item), item.Duration, item.Stack))
} }
return lines return lines
} }