You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.0 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace CDPShared
  8. {
  9. public class MinLogging
  10. {
  11. public string LoggerName = string.Empty;
  12. static string LogFile = @"CircleViewer.txt";
  13. static MinLogging()
  14. {
  15. try
  16. {
  17. LogFile = Path.Combine(Constants.CircleFolder, LogFile);
  18. if (File.Exists(LogFile))
  19. {
  20. System.IO.FileInfo fi = new System.IO.FileInfo(LogFile);
  21. if (fi.Length > 10000000) // don't let the log file get larger than 10MB
  22. {
  23. try
  24. {
  25. File.Delete(LogFile);
  26. }
  27. catch (Exception e)
  28. {
  29. Trace.WriteLine(e);
  30. }
  31. }
  32. }
  33. }
  34. catch (Exception ex)
  35. {
  36. Trace.WriteLine(ex);
  37. }
  38. }
  39. public static void LogIt(string str)
  40. {
  41. try
  42. {
  43. // only log to file if THIS is the same or higher level of detail as my desired logging level
  44. str = string.Format("{0}|{1}|{2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, str);
  45. lock (LogFile)
  46. {
  47. File.AppendAllText(LogFile, str + Environment.NewLine);
  48. if (str.Length < 512)
  49. {
  50. byte[] data = Encoding.ASCII.GetBytes(str);
  51. }
  52. else
  53. {
  54. byte[] data = Encoding.ASCII.GetBytes(string.Format($"String to long. Length: {str.Length}"));
  55. }
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. Trace.WriteLine(ex);
  61. }
  62. }
  63. }
  64. public class LogMethod : IDisposable
  65. {
  66. private string _methodName;
  67. private Stopwatch _sw;
  68. /// <summary>
  69. /// Ctor now private - just called from the static Log method
  70. /// </summary>
  71. /// <param name="methodName">The name of the method being logged</param>
  72. private LogMethod(string methodName)
  73. {
  74. _methodName = methodName;
  75. _sw = new Stopwatch();
  76. _sw.Start();
  77. string msg = string.Format(">> Entering {0}", _methodName);
  78. MinLogging.LogIt(msg);
  79. }
  80. /// <summary>
  81. /// Tidy up
  82. /// </summary>
  83. public void Dispose()
  84. {
  85. _sw.Stop();
  86. string msg = string.Format("<< Exiting {0}: elapsed Time: {1} ms", _methodName, _sw.ElapsedMilliseconds);
  87. MinLogging.LogIt(msg);
  88. }
  89. public static IDisposable Log(string callingMethodTypeHardcode)
  90. {
  91. return new LogMethod(callingMethodTypeHardcode);
  92. }
  93. }
  94. }