using System; using System.IO; using System.Threading.Tasks; namespace ReleaseHelper.Utils { public static class Log { private readonly static object _lock = new object(); private static string logAll = ""; private static string logTmp = ""; private static readonly string logPath = Path.Combine(Environment.CurrentDirectory, "log"); /// /// 日志处理的委托 /// /// 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(logTmp); #endif //Forms.Instances.MainEntrance().SetLog(Variables.Variables.LogTmp); Save(force); } } /// /// 保存信息 /// /// public static void Save(bool force = false, string filename = null) { //lock (Variables.Variables.LogTmp) //{ if (force || logTmp.Length > 30000) { //if (!File.Exists(Variables.Variables.AppLogPath)) //{ // string p = Variables.Variables.AppLogPath; // if (!Directory.Exists(p)) // { // Directory.CreateDirectory(Variables.Variables.AppLogPath); // } //} if (string.IsNullOrEmpty(filename)) { filename = Today(); } //File.AppendAllText(Path.Combine(Variables.Variables.AppLogPath, $"{filename}.txt"), Variables.Variables.LogTmp, System.Text.Encoding.UTF8); string txt; lock (_lock) { txt = logTmp; logTmp = ""; } Task.Run(() => { FileExtensions.AppendAllText(Path.Combine(logPath, $"{filename}.txt"), txt); }); } //} } } }