Slowlogger.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. namespace Wayne.Lib.Log.SlowLog
  6. {
  7. internal class Slowlogger : DisposableBase, ISlowLogger
  8. {
  9. private static readonly IIdentifiableEntity LoggingEntity = new IdentifiableEntity(IdentifiableEntity.NoId, "SlowLog", "", null);
  10. private readonly Stopwatch stopwatch = Stopwatch.StartNew();
  11. private readonly string context;
  12. private readonly TimeSpan threshold;
  13. readonly List<CheckpointInstant> checkpoints = new List<CheckpointInstant>();
  14. class CheckpointInstant
  15. {
  16. public TimeSpan At { get; set; }
  17. public string Name { get; set; }
  18. }
  19. public Slowlogger(string context, TimeSpan threshold)
  20. {
  21. this.context = context;
  22. this.threshold = threshold;
  23. }
  24. protected override void DoDispose()
  25. {
  26. stopwatch.Stop();
  27. if (stopwatch.Elapsed > threshold)
  28. {
  29. using (DebugLogger debugLogger = new DebugLogger(LoggingEntity))
  30. {
  31. if (debugLogger.IsActive())
  32. {
  33. StringBuilder sb = new StringBuilder();
  34. sb.AppendFormat(":::::: SLOWLOG ::::: [{0}] Expected to take less than {1} but took {2}", context, threshold, stopwatch.Elapsed);
  35. if (checkpoints.Count > 0)
  36. {
  37. TimeSpan lastTimeSpan = checkpoints[0].At;
  38. foreach (var checkpointInstant in checkpoints)
  39. {
  40. sb.AppendLine();
  41. sb.AppendFormat(" Checkpoint {0,45} @ {1}, delta {2}", checkpointInstant.Name, checkpointInstant.At, checkpointInstant.At - lastTimeSpan);
  42. lastTimeSpan = checkpointInstant.At;
  43. }
  44. }
  45. debugLogger.Add(sb);
  46. }
  47. }
  48. }
  49. }
  50. public void Checkpoint(string checkpointName)
  51. {
  52. checkpoints.Add(new CheckpointInstant()
  53. {
  54. Name = checkpointName,
  55. At = stopwatch.Elapsed
  56. });
  57. }
  58. }
  59. }