using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Bro.Common.Helper { public class LoggerHelper { public string LogPath { get; set; } public string LogPrefix { get; set; } public LoggerHelper() { } public LoggerHelper(string logPath, string logPrefix) { LogPath = logPath; LogPrefix = logPrefix; } readonly ConcurrentQueue _logQueue = new ConcurrentQueue(); Task _logTask = null; readonly object _logLock = new object(); public async void LogAsync(LogMsg msg) { await Task.Run(() => { _logQueue.Enqueue(msg); lock (_logLock) { if (_logTask == null) { _logTask = Task.Run(() => { if (!Directory.Exists(LogPath)) { Directory.CreateDirectory(LogPath); } while (true) { if (_logQueue.Count > 0) { string filePath = Path.Combine(LogPath, $"Log_{(string.IsNullOrWhiteSpace(LogPrefix) ? "" : (LogPrefix + "_"))}{DateTime.Now.ToString("yyyyMMdd")}.txt"); using (StreamWriter writer = new StreamWriter(filePath, true, System.Text.Encoding.UTF8)) { while (_logQueue.Count > 0) { if (_logQueue.TryDequeue(out LogMsg log)) { writer.WriteLine($"{log.LogTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t{log.Prefix}\t{log.Msg}"); } } writer.Flush(); writer.Close(); } } Thread.Sleep(1000); } }); } } }); } public void LogAsync(DateTime dt, string prefix, string msg) { LogAsync(new LogMsg(dt, prefix, msg)); } } public class LogMsg { public DateTime LogTime { get; set; } public string Prefix { get; set; } public string Msg { get; set; } public LogMsg() { } public LogMsg(DateTime dt, string prefix, string msg) { LogTime = dt; Prefix = prefix; Msg = msg; } } }