Program.Log.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Copyright (C) 2012-2016 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using Utilities;
  12. namespace ISCSIConsole
  13. {
  14. public partial class Program
  15. {
  16. private static FileStream m_logFile;
  17. public static bool OpenLogFile(string logFilePath)
  18. {
  19. try
  20. {
  21. // We must avoid using buffered writes, using it will negatively affect the performance and reliability.
  22. // Note: once the file system write buffer is filled, Windows may delay any (buffer-dependent) pending write operations, which will create a deadlock.
  23. m_logFile = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, 0x1000, FileOptions.WriteThrough);
  24. return true;
  25. }
  26. catch
  27. {
  28. return false;
  29. }
  30. }
  31. public static void CloseLogFile()
  32. {
  33. if (m_logFile != null)
  34. {
  35. lock (m_logFile)
  36. {
  37. m_logFile.Close();
  38. m_logFile = null;
  39. }
  40. }
  41. }
  42. public static void OnLogEntry(object sender, LogEntry entry)
  43. {
  44. if (m_logFile != null && entry.Severity != Severity.Trace)
  45. {
  46. lock (m_logFile)
  47. {
  48. StreamWriter writer = new StreamWriter(m_logFile);
  49. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
  50. writer.WriteLine("{0} {1} [{2}] {3}", entry.Severity.ToString().PadRight(12), timestamp, entry.Source, entry.Message);
  51. writer.Flush();
  52. }
  53. }
  54. }
  55. }
  56. }