log.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package log
  2. import (
  3. "fmt"
  4. "time"
  5. "k8s.io/klog"
  6. )
  7. func Errorf(format string, a ...interface{}) {
  8. klog.Errorf(fmt.Sprintf("[Error] %s", format), a...)
  9. }
  10. func Warningf(format string, a ...interface{}) {
  11. klog.V(2).Infof(fmt.Sprintf("[Warning] %s", format), a...)
  12. }
  13. func Infof(format string, a ...interface{}) {
  14. klog.V(3).Infof(fmt.Sprintf("[Info] %s", format), a...)
  15. }
  16. func Profilef(format string, a ...interface{}) {
  17. klog.V(3).Infof(fmt.Sprintf("[Profiler] %s", format), a...)
  18. }
  19. func Debugf(format string, a ...interface{}) {
  20. klog.V(4).Infof(fmt.Sprintf("[Debug] %s", format), a...)
  21. }
  22. func Profile(start time.Time, name string) {
  23. elapsed := time.Since(start)
  24. Profilef("%s: %s", elapsed, name)
  25. }
  26. func ProfileWithThreshold(start time.Time, threshold time.Duration, name string) {
  27. elapsed := time.Since(start)
  28. if elapsed > threshold {
  29. Profilef("%s: %s", elapsed, name)
  30. }
  31. }
  32. type Profiler struct {
  33. profiles map[string]time.Duration
  34. starts map[string]time.Time
  35. }
  36. func NewProfiler() *Profiler {
  37. return &Profiler{
  38. profiles: map[string]time.Duration{},
  39. starts: map[string]time.Time{},
  40. }
  41. }
  42. func (p *Profiler) Start(name string) {
  43. if p == nil {
  44. return
  45. }
  46. p.starts[name] = time.Now()
  47. }
  48. func (p *Profiler) Stop(name string) time.Duration {
  49. if p == nil {
  50. return 0
  51. }
  52. if start, ok := p.starts[name]; ok {
  53. elapsed := time.Since(start)
  54. p.profiles[name] += elapsed
  55. return elapsed
  56. }
  57. return 0
  58. }
  59. func (p *Profiler) Log(name string) {
  60. if p == nil {
  61. return
  62. }
  63. Profilef("%s: %s", p.profiles[name], name)
  64. }
  65. func (p *Profiler) LogAll() {
  66. if p == nil {
  67. return
  68. }
  69. // Print profiles, largest to smallest. (Inefficienct, but shouldn't matter.)
  70. print := map[string]time.Duration{}
  71. for name, value := range p.profiles {
  72. print[name] = value
  73. }
  74. for len(print) > 0 {
  75. largest := ""
  76. for name := range print {
  77. if print[name] > print[largest] {
  78. largest = name
  79. }
  80. }
  81. Profilef("%s: %s", print[largest], largest)
  82. delete(print, largest)
  83. }
  84. }