stats.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package appsrv
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "yunion.io/x/jsonutils"
  20. )
  21. func doStatsHandler(stats *jsonutils.JSONArray, method, path string, hi, total *SHandlerInfo) {
  22. s := jsonutils.NewDict()
  23. s.Add(jsonutils.NewString(method), "method")
  24. s.Add(jsonutils.NewString(path), "path")
  25. s.Add(jsonutils.NewString(hi.GetName(nil)), "name")
  26. s.Add(jsonutils.NewInt(hi.counter2XX.hit), "hit.2XX")
  27. s.Add(jsonutils.NewFloat64(hi.counter2XX.duration), "duration.2XX")
  28. s.Add(jsonutils.NewInt(hi.counter4XX.hit), "hit.4XX")
  29. s.Add(jsonutils.NewFloat64(hi.counter4XX.duration), "duration.4XX")
  30. s.Add(jsonutils.NewInt(hi.counter5XX.hit), "hit.5XX")
  31. s.Add(jsonutils.NewFloat64(hi.counter5XX.duration), "duration.5XX")
  32. total.counter2XX.hit += hi.counter2XX.hit
  33. total.counter2XX.duration += hi.counter2XX.duration
  34. total.counter4XX.hit += hi.counter4XX.hit
  35. total.counter4XX.duration += hi.counter4XX.duration
  36. total.counter5XX.hit += hi.counter5XX.hit
  37. total.counter5XX.duration += hi.counter5XX.duration
  38. stats.Add(s)
  39. }
  40. func StatisticHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  41. app := AppContextApp(ctx)
  42. stats := jsonutils.NewArray()
  43. total := newHandlerInfo("", nil, nil, nil, "", nil)
  44. doStatsHandler(stats, "*", "*", &app.defHandlerInfo, total)
  45. for method, root := range app.roots {
  46. root.Walk(func(path string, data interface{}) {
  47. hi := data.(*SHandlerInfo)
  48. doStatsHandler(stats, method, path, hi, total)
  49. })
  50. }
  51. result := jsonutils.NewDict()
  52. result.Add(stats, "paths")
  53. result.Add(jsonutils.NewInt(total.counter2XX.hit), "hit.2XX")
  54. result.Add(jsonutils.NewFloat64(total.counter2XX.duration), "duration.2XX")
  55. result.Add(jsonutils.NewInt(total.counter4XX.hit), "hit.4XX")
  56. result.Add(jsonutils.NewFloat64(total.counter4XX.duration), "duration.4XX")
  57. result.Add(jsonutils.NewInt(total.counter5XX.hit), "hit.5XX")
  58. result.Add(jsonutils.NewFloat64(total.counter5XX.duration), "duration.5XX")
  59. fmt.Fprintf(w, "%s", result.String())
  60. }