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.

104 lines
3.1 KiB

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