SystemFileLogs.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace HPSocketCS.Extended
  6. {
  7. public class SystemFileLogs
  8. {
  9. public SystemFileLogs() {
  10. }
  11. static string logsPath =HPSocketCS.Extended.CommonLibrary.GetFullDirectoryPath(HPSocketCS.Extended.CommonLibrary.BasePath) + "Logs\\"+DateTime.Now.ToString("yyyy-MM-dd")+".log";
  12. /// <summary>
  13. /// 分割日志文件
  14. /// </summary>
  15. /// <param name="fileName"></param>
  16. public static void SplitLogFile(string fileName)
  17. {
  18. try
  19. {
  20. if (System.IO.File.Exists(fileName))
  21. {
  22. System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
  23. if ((fileInfo.Length / 1024 / 1024) >= 5)
  24. {
  25. string newFileFullName = System.IO.Path.GetDirectoryName(fileName) + "\\" + System.IO.Path.GetFileNameWithoutExtension(fileName) + "(" + DateTime.Now.ToString("HH:mm:ss") + ").log";
  26. System.IO.File.Copy(fileName, newFileFullName);
  27. string msg = "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】日志文件过大,已被分割保存,可以当前日志目录找到...\r\n";
  28. System.IO.File.WriteAllText(fileName, msg, Encoding.UTF8);
  29. }
  30. }
  31. }
  32. catch { }
  33. }
  34. /// <summary>
  35. /// 写日志
  36. /// </summary>
  37. /// <param name="txt">日志内容</param>
  38. public static void WriteLogs(string txt)
  39. {
  40. SystemFileLogs.WriteLogs(txt, logsPath);
  41. }
  42. /// <summary>
  43. /// 写日志
  44. /// </summary>
  45. /// <param name="txt">日志内容</param>
  46. public static void WriteLogs(string txt, HPSocketCS.Extended.CustomTraceListener _TraceListenerLog)
  47. {
  48. if (_TraceListenerLog != null)
  49. {
  50. _TraceListenerLog.WriteLine( "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】"+txt);
  51. }
  52. SystemFileLogs.WriteLogs(txt, logsPath);
  53. }
  54. /// <summary>
  55. /// 写日志
  56. /// </summary>
  57. /// <param name="txt">日志内容</param>
  58. /// <param name="fullPath">日志文件全路径</param>
  59. static void WriteLogs(string txt, string fullPath)
  60. {
  61. try
  62. {
  63. if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(fullPath)))
  64. {
  65. System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
  66. }
  67. SplitLogFile(fullPath);
  68. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
  69. {
  70. sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】" + txt);
  71. sw.Flush();
  72. sw.Close();
  73. }
  74. }
  75. catch { }
  76. }
  77. }
  78. }