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.

92 lines
2.8 KiB

  1. using IllusionPlugin.Logging;
  2. using Ionic.Zlib;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace IllusionInjector.Logging.Printers
  11. {
  12. public abstract class GZFilePrinter : LogPrinter
  13. {
  14. [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  15. static extern bool CreateHardLink(
  16. string lpFileName,
  17. string lpExistingFileName,
  18. IntPtr lpSecurityAttributes
  19. );
  20. [DllImport("Kernel32.dll")]
  21. static extern Int32 GetLastError();
  22. private FileInfo fileInfo;
  23. protected StreamWriter fileWriter;
  24. private GZipStream zstream;
  25. private FileStream fstream;
  26. protected abstract FileInfo GetFileInfo();
  27. private void InitLog()
  28. {
  29. try
  30. {
  31. if (fileInfo == null)
  32. { // first init
  33. fileInfo = GetFileInfo();
  34. var ext = fileInfo.Extension;
  35. fileInfo = new FileInfo(fileInfo.FullName + ".gz");
  36. fileInfo.Create().Close();
  37. var symlink = new FileInfo(Path.Combine(fileInfo.DirectoryName, $"latest{ext}.gz"));
  38. if (symlink.Exists) symlink.Delete();
  39. try
  40. {
  41. if (!CreateHardLink(symlink.FullName, fileInfo.FullName, IntPtr.Zero))
  42. {
  43. Logger.log.Error($"Hardlink creation failed {GetLastError()}");
  44. }
  45. }
  46. catch (Exception e)
  47. {
  48. Logger.log.Error("Error creating latest hardlink!");
  49. Logger.log.Error(e);
  50. }
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. Logger.log.Error("Error initializing log!");
  56. Logger.log.Error(e);
  57. }
  58. }
  59. public override sealed void StartPrint()
  60. {
  61. InitLog();
  62. fstream = fileInfo.Open(FileMode.Append, FileAccess.Write);
  63. zstream = new GZipStream(fstream, CompressionMode.Compress)
  64. {
  65. FlushMode = FlushType.Full
  66. };
  67. fileWriter = new StreamWriter(zstream, Encoding.UTF8);
  68. }
  69. public override sealed void EndPrint()
  70. {
  71. fileWriter.Flush();
  72. zstream.Flush();
  73. fstream.Flush();
  74. fileWriter.Close();
  75. zstream.Close();
  76. fstream.Close();
  77. fileWriter.Dispose();
  78. zstream.Dispose();
  79. fstream.Dispose();
  80. }
  81. }
  82. }