Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. namespace Logging
  2. {
  3. using System;
  4. using System.Diagnostics;
  5. using System.Threading;
  6.  
  7. public interface ILogSink
  8. {
  9. void Log(string message);
  10. }
  11.  
  12. public static class Log
  13. {
  14. private static Stopwatch MasterWatch;
  15.  
  16. public static ILogSink LogSink
  17. {
  18. get;
  19. set;
  20. }
  21.  
  22. public static void Info(string message)
  23. {
  24. LogSink.Log("[INFO] " + message);
  25. }
  26.  
  27. public static void Info(string format, params object[] args)
  28. {
  29. LogSink.Log("[INFO] " + string.Format(format, args));
  30. }
  31.  
  32. public static PerfBlock Perf(string message)
  33. {
  34. return new PerfBlock(message);
  35. }
  36.  
  37. public static PerfBlock Perf(string format, params object[] args)
  38. {
  39. return new PerfBlock(string.Format(format, args));
  40. }
  41.  
  42. public static void StartMasterWatch()
  43. {
  44. MasterWatch = Stopwatch.StartNew();
  45. }
  46.  
  47. public static void StoppMasterWatch(string message)
  48. {
  49. MasterWatch.Stop();
  50. Log.LogSink.Log($"[PERF] ************** {message} [{MasterWatch.ElapsedMilliseconds}ms ************]");
  51. }
  52.  
  53. public struct PerfBlock : IDisposable
  54. {
  55. private static int nextLevel;
  56. private readonly string message;
  57. private readonly Stopwatch stopwatch;
  58. private readonly int level;
  59.  
  60. public PerfBlock(string message)
  61. {
  62. this.message = message;
  63. this.stopwatch = Stopwatch.StartNew();
  64. this.level = Interlocked.Increment(ref nextLevel);
  65. }
  66.  
  67. public void Dispose()
  68. {
  69. this.stopwatch.Stop();
  70. Log.LogSink.Log($"[PERF] {new string(' ', this.level * 4)} {this.message} [{this.stopwatch.ElapsedMilliseconds}ms]");
  71. Interlocked.Decrement(ref nextLevel);
  72. }
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement