日志log2

时间:2021-09-07 20:14:20
 public class LoggerHelper2
    {
        private static ConcurrentQueue<string> CqMsg = null;

        private static string logFilePath = @"D:\log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

        static LoggerHelper2()
        {
            CqMsg = new ConcurrentQueue<string>();
            //存入日志
            Run();
        }

        public static void WriteLog(string strLog)
        {
            if (string.IsNullOrEmpty(strLog))
            {
                return;
            }
            strLog = strLog.Replace("\n", "\r\n");

            if (!File.Exists(logFilePath))
            {
                File.Create(logFilePath).Dispose();
            }
            using (StreamWriter sw = File.AppendText(logFilePath))
            {
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + "]  " + strLog);
            }
        }

        public static void Run()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    string tmsg = string.Empty;
                    )
                    {
                        CqMsg.TryDequeue(out tmsg);
                    }
                    if (!String.IsNullOrEmpty(tmsg))
                    {
                        WriteLog(tmsg);
                    }
                    )
                    {
                        Thread.Sleep();
                    }
                }
            });
        }

        public static void WriteLogAsync(string strlog)
        {
            CqMsg.Enqueue(strlog);
        }
        public static void WriteLogAsync(string filepath, string strlog)
        {
            if (string.IsNullOrEmpty(filepath))
            {
                WriteLogAsync(strlog);
            }
            else
            {
                logFilePath = filepath;
                CqMsg.Enqueue(strlog);
            }
        }
    }

使用

  Parallel.For(, , index =>
            {
                string msg1 = "test" + index.ToString();
                LoggerHelper2.WriteLogAsync(msg1);
            });