| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- 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();
- /// <summary>
- /// 当前全部日志
- /// </summary>
- private static string LogAll = "";
- /// <summary>
- /// 临时日志
- /// </summary>
- private static string LogTmp = "";
- /// <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(Variables.Variables.LogTmp);
- //#endif
- Save(force);
- }
- }
- /// <summary>
- /// 保存信息
- /// </summary>
- /// <param name="force"></param>
- 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);
- });
- }
- }
- }
- }
|