当前位置: 首页 > 科技观察

Statsviz

时间:2023-03-21 23:54:35 科技观察

,Go程序运行时数据统计的可视化工具,转载请联系GoYedu公众号。今天给大家介绍一款Go程序运行时数据统计的实时可视化工具statsvizhttps://github.com/arl/statsviz它的图形化展示对于我们了解Go程序的GC行为和内存开销非常有用!使用Simple也很有用:1.gogetgithub.com/arl/statsviz2.在http.ServeMux:=http.NewServeMux()statsviz.Register(mux)上注册mux或使用默认的http注册:statsviz.RegisterDefault()如果你的程序不是http应用,那么你可以添加如下代码启动gofunc(){log.Println(http.ListenAndServe("localhost:6060",nil))}()这段代码,我相信大家很熟悉吧~我们启动的时候直接在浏览器打开即可:http://localhost:6060/debug/statsviz/看起来很酷很高大上,其实主要是依赖Go提供的runtimestats对我们来说。我们来看看它的一些代号:1。websockethandler//NewWsHandlerreturnsahandlerthatupgradestheHTTPserverconnectiontotheWebSocket//protocolandsendsapplicationstatisticsatthegivenfrequency.////Iftheupgradefails,anHTTPerrorresponseissenttotheclient.funcNewWsHandler(frequencytime.Duration)http.HandlerFunc{returnfunc(whttp.ResponseWriter,r*http.Request){varupgrader=websocket.Upgrader{ReadBufferSize:1024,WriteBufferSize:1024,}ws,err:=upgrader.Upgrade(w,r,nil)iferr!=nil{return}deferws.Close()//明确忽略此错误。我们不想发送垃圾邮件标准输出//每次网络套接字连接的另一端关闭。_=sendStats(ws,frequency)}}2.sendStats//sendStatsindefinitelysendruntimestatisticonthewebsocketconnection.funcsendStats(conn*websocket.Conn,frequencytime.Duration)error{tick:=time.NewTicker(frequency)defertick.Stop()var(statsstatserrerror)forrangetick.C{runtime.ReadMemStats(&stats.Mem)stats.NumGoroutine=runtime.NumGoroutine()iferr=conn.WriteJSON(stats);err!=nil{break}}returnerr}3.其实际这个项目比较核心的代码是前端JavaScript代码:m.pushData=function(ts,allStats){data.times.push(ts);//timestampconstmemStats=allStats.Mem;data.gcfraction.push(memStats.GCCPUFraction);data.goroutines.push(allStats.NumGoroutine);data.heap[idxHeapAlloc].push(memStats.HeapAlloc);data.heap[idxHeapSys].push(memStats.HeapSys);data.heap[idxHeapIdle].push(memStats.HeapIdle);data.heap[idxHeapInuse].push(memStats.HeapInuse);data.heap[idxHeapNextGC].push(memStats.NextGC);data.mspanMCache[idxMSpanMCacheMSpanInUse].push(memStats.MSpanInuse);data.mspanMCache[idxMSpanMCacheMSpanSys].push(memStats.MSpanSys);data.mspanMCache[idxMSpanMSpanMSCacheInUse].push(memStats.MCacheInuse);data.mspanMCachem(SpanMSpanMSpanMSpanSys]StpMSCs).MCacheSys数据。;data.objects[idxObjectsLive].push(memStats.Mallocs-memStats.Frees);data.objects[idxObjectsLookups].push(memStats.Lookups);data.objects[idxObjectsHeap].push(memStats.HeapObjects);for(leti=0;i

最新推荐
猜你喜欢