| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- 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");
- /// <summary>
- /// 日志处理的委托
- /// </summary>
- /// <param name="s"></param>
- public delegate void SetLog(string s);
- /// <summary>
- /// 具体委托的实例
- /// </summary>
- 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");
- }
- /// <summary>
- /// 记录错误
- /// </summary>
- /// <param name="exception"></param>
- public static void Error(Exception exception)
- {
- WriteLine(exception.StackTrace, "error", force: true);
- }
- /// <summary>
- /// 记录信息
- /// </summary>
- /// <param name="s"></param>
- /// <param name="t"></param>
- /// <param name="filename"></param>
- 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);
- }
- }
- /// <summary>
- /// 保存信息
- /// </summary>
- /// <param name="force"></param>
- 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);
- });
- }
- //}
- }
- }
- }
|