AdvConsole.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. namespace HyperCube.Utils
  4. {
  5. public static class AdvConsole
  6. {
  7. private const string LOGS_FOLDER = "Logs";
  8. //private const string LOGS_ARCHIVE_FOLDER = "Archives";
  9. private const string LOG_FILE_NAME = "current.log";
  10. static StreamWriter _writer;
  11. static TextWriter _oldOut = Console.Out;
  12. static string _folderPath;
  13. static string _fullPath;
  14. public static void Initialize()
  15. {
  16. _folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LOGS_FOLDER);
  17. _fullPath = Path.Combine(_folderPath, LOG_FILE_NAME);
  18. _oldOut = Console.Out;
  19. if (File.Exists(_fullPath))
  20. File.Move(_fullPath, Path.Combine(_folderPath, $"{DateTime.Now:yyyy.MM.dd_HH-mm-ss}.log"));
  21. }
  22. public static void WriteLine(string message)
  23. {
  24. try
  25. {
  26. if (!Directory.Exists(_folderPath))
  27. Directory.CreateDirectory(_folderPath);
  28. if (File.Exists(_fullPath))
  29. _writer = File.AppendText(_fullPath);
  30. else
  31. _writer = File.CreateText(_fullPath);
  32. }
  33. catch (Exception e)
  34. {
  35. Console.WriteLine($"Cannot open [{_fullPath}] for writing");
  36. Console.WriteLine(e.Message);
  37. return;
  38. }
  39. string fullmessage = $"{DateTime.Now:yyyy.MM.dd HH:mm:ss.fff}: {message}";
  40. Console.SetOut(_writer);
  41. Console.WriteLine(fullmessage);
  42. Console.SetOut(_oldOut);
  43. Console.WriteLine(fullmessage);
  44. _writer.Close();
  45. }
  46. }
  47. }