using System; using System.Collections.Concurrent; using System.IO; using System.Threading.Tasks; namespace IMCS.CCS { public class Log { private static Log _log = new Log(); public static Log Instance { get { return _log; } } LogDefaultList item = new LogDefaultList(); string Path = AppDomain.CurrentDomain.BaseDirectory + "webApiLog"; ConcurrentQueue qs = new ConcurrentQueue(); System.IO.StreamWriter streamWriter; public Log() { if (!System.IO.Directory.Exists(Path)) { Directory.CreateDirectory(Path); } ThreadWrite(); } public void WriteLogAdd(string msg, string path=null) { qs.Enqueue(new LogDefaultList() { msg = msg, path = path }); } public delegate void DelShowLog(string msg); public event DelShowLog EveShowLog; private void WriteLog(string msg, string path) { try { if (string.IsNullOrEmpty(path)) { path = DateTime.Now.ToString("yyyy-MM-dd"); } else { path = path + " " + DateTime.Now.ToString("yyyy-MM-dd"); } streamWriter = new System.IO.StreamWriter(Path + "\\" + path + ".txt", true); streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg); streamWriter.Close(); this.EveShowLog?.Invoke(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "-->>>" + msg); }catch(Exception ex) { Console.WriteLine("写入日志文件失败:" + ex.Message); streamWriter.Close(); } } private void ThreadWrite() { Task.Factory.StartNew(() => { while (true) { System.Threading.Thread.Sleep(20); if (qs.Count > 0) { if (qs.TryDequeue(out item)) { WriteLog(item.msg, item.path); } } } }); } } public class LogDefaultList { public string path { get; set; } public string msg { get; set; } } }