using DaJiaoYan.Variables; using System; using System.IO; using System.Threading.Tasks; namespace DaJiaoYan.Utils { internal class Log { private readonly static object _lock = new object(); /// /// 当前全部日志 /// private static string LogAll = ""; /// /// 临时日志 /// private static string LogTmp = ""; /// /// 日志处理的委托 /// /// public delegate void SetLog(string s); /// /// 具体委托的实例 /// //public static SetLog DoSetLog; public static string Now() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } private static string Today() { return DateTime.Now.ToString("yyyy-MM-dd"); } /// /// 记录错误 /// /// public static void Error(Exception exception) { WriteLine(exception.StackTrace, "error", force: true); } /// /// 记录信息 /// /// /// /// public static void WriteLine(string s, string t = "log", string filename = null, bool force = false) { if (s != null) { string info = $"{Now()} [{t}] {s}\r\n"; Console.Write(info); lock (_lock) { LogAll = string.Concat(LogAll, info); LogTmp = string.Concat(LogTmp, info); } //#if DEBUG // DoSetLog?.Invoke(Variables.Variables.LogTmp); //#endif Save(force); } } /// /// 保存信息 /// /// public static void Save(bool force = false, string filename = null) { if (force || LogTmp.Length > 30000) { if (string.IsNullOrEmpty(filename)) { filename = Today(); } string txt; lock (_lock) { txt = LogTmp; LogTmp = ""; } Task.Run(() => { FileExts.AppendAllText(Path.Combine(Const.LOG_DIR, $"{filename}.txt"), txt); }); } } } }