Program.Log.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Utilities;
  6. namespace ISCSIConsole
  7. {
  8. public partial class Program
  9. {
  10. private static FileStream m_logFile;
  11. public static void OpenLogFile(string logFilePath)
  12. {
  13. try
  14. {
  15. // We must avoid using buffered writes, using it will negatively affect the performance and reliability.
  16. // Note: once the file system write buffer is filled, Windows may delay any (buffer-dependent) pending write operations, which will create a deadlock.
  17. m_logFile = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, 0x1000, FileOptions.WriteThrough);
  18. }
  19. catch
  20. {
  21. Console.WriteLine("Cannot open log file");
  22. }
  23. }
  24. public static void CloseLogFile()
  25. {
  26. if (m_logFile != null)
  27. {
  28. lock (m_logFile)
  29. {
  30. m_logFile.Close();
  31. m_logFile = null;
  32. }
  33. }
  34. }
  35. public static void OnLogEntry(object sender, LogEntry entry)
  36. {
  37. if (m_logFile != null && entry.Severity != Severity.Trace)
  38. {
  39. lock (m_logFile)
  40. {
  41. StreamWriter writer = new StreamWriter(m_logFile);
  42. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
  43. writer.WriteLine("{0} {1} [{2}] {3}", entry.Severity.ToString().PadRight(12), timestamp, entry.Source, entry.Message);
  44. writer.Flush();
  45. }
  46. }
  47. }
  48. }
  49. }