using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YG { 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+"YGLog"; 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) { if (string.IsNullOrEmpty(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); } 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; } } }