123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Concurrent;
- using System.IO;
- using System.Threading.Tasks;
- namespace WCS
- {
- public class CollectDataLog
- {
- private static CollectDataLog _log = new CollectDataLog();
- public static CollectDataLog Instance { get { return _log; } }
- DataDefaultList item = new DataDefaultList();
- string Path = AppDomain.CurrentDomain.BaseDirectory + "webApiLog/采集数据";
- ConcurrentQueue<DataDefaultList> qs = new ConcurrentQueue<DataDefaultList>();
- System.IO.StreamWriter streamWriter;
- public CollectDataLog()
- {
- if (!System.IO.Directory.Exists(Path))
- {
- Directory.CreateDirectory(Path);
- }
- ThreadWrite();
- }
- public void WriteLogAdd(string msg, string path = null)
- {
- qs.Enqueue(new DataDefaultList() { 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");
- }
- 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);
- }
- 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 DataDefaultList
- {
- public string path { get; set; }
- public string msg { get; set; }
- }
- }
|