FileLogTarget.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace Ryujinx.Common.Logging
  5. {
  6. public class FileLogTarget : ILogTarget
  7. {
  8. private readonly StreamWriter _logWriter;
  9. private readonly ILogFormatter _formatter;
  10. private readonly string _name;
  11. string ILogTarget.Name { get => _name; }
  12. public FileLogTarget(string path, string name)
  13. : this(path, name, FileShare.Read, FileMode.Append)
  14. { }
  15. public FileLogTarget(string path, string name, FileShare fileShare, FileMode fileMode)
  16. {
  17. // Ensure directory is present
  18. DirectoryInfo logDir = new DirectoryInfo(Path.Combine(path, "Logs"));
  19. logDir.Create();
  20. // Clean up old logs, should only keep 3
  21. FileInfo[] files = logDir.GetFiles("*.log").OrderBy((info => info.CreationTime)).ToArray();
  22. for (int i = 0; i < files.Length - 2; i++)
  23. {
  24. files[i].Delete();
  25. }
  26. string version = ReleaseInformation.GetVersion();
  27. // Get path for the current time
  28. path = Path.Combine(logDir.FullName, $"Ryujinx_{version}_{DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")}.log");
  29. _name = name;
  30. _logWriter = new StreamWriter(File.Open(path, fileMode, FileAccess.Write, fileShare));
  31. _formatter = new DefaultLogFormatter();
  32. }
  33. public void Log(object sender, LogEventArgs args)
  34. {
  35. _logWriter.WriteLine(_formatter.Format(args));
  36. _logWriter.Flush();
  37. }
  38. public void Dispose()
  39. {
  40. _logWriter.WriteLine("---- End of Log ----");
  41. _logWriter.Flush();
  42. _logWriter.Dispose();
  43. }
  44. }
  45. }