using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace GummingCommon { /// /// this is debug class,not used /// public class MonitorLog { private static StringBuilder logContent = new StringBuilder(); /// /// 防止并发对象 /// private static Object lockobj = new Object(); private static DateTime lastTime = DateTime.Now; /// /// /// /// /// public static bool WriteLog(string log) { bool returnValue; double ticket = DateTime.Now.Subtract(lastTime).TotalMilliseconds; logContent.AppendLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + " - " + ticket + " " + log); lastTime = DateTime.Now; returnValue = WriteLog(); return returnValue; } /// /// 产生文件名 /// /// private static string GenerateFileName() { string path = AppDomain.CurrentDomain.BaseDirectory + @"log\debug\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path + "Monitor" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + " " + System.Guid.NewGuid().ToString() + ".txt"; } public static int maxFlushSize = 1000000; /// /// 记录监控日志 /// /// 日志内容 /// public static bool WriteLog() { bool returnValue = true; lock (logContent) //防止并发 { if (logContent.Length >= maxFlushSize) { GC.Collect();//强制垃圾回收 int writtenSize = FlushLog(); //将监控日志写入文件 if (writtenSize > 0) { logContent.Clear(); } else if (writtenSize == -1) //写入日志失败 { returnValue = false; } } } return returnValue; } public static int FlushLog() { int returnValue = -1; try { if (logContent.Length > 0) { StreamWriter sw = File.CreateText(GenerateFileName()); returnValue = logContent.Length; sw.Write(logContent.ToString(0, returnValue)); sw.Close(); logContent.Clear(); } } catch { returnValue = -1; } return returnValue; } } }