1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using System;
- using System.Collections.Concurrent;
- using System.IO;
- using System.Threading.Tasks;
- namespace WCS
- {
- 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<LogDefaultList> qs = new ConcurrentQueue<LogDefaultList>();
- 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");
- }
- 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 LogDefaultList
- {
- public string path { get; set; }
-
- public string msg { get; set; }
- }
- }
|