This commit is contained in:
龙腾猫跃 committed 2026-05-07 07:11:26 +08:00
1 parent 501180c9e8
commit c017654b6a
3 files changed
+60 -37

No files matched your search

+21 -1
View File
@@ -11,6 +11,24 @@ public static class ExceptionExtensions {
return ex; return ex;
} }
/// <summary>
/// 将异常所有的 <see cref="Exception.InnerException"/> 展开。
/// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。
/// </summary>
public static IEnumerable<Exception> Flatten(this Exception ex) {
var toFlatten = new Stack<Exception>();
toFlatten.Push(ex);
while (toFlatten.Any()) {
var current = toFlatten.Pop();
yield return current;
if (current is AggregateException ag) {
foreach (var inner in ag.InnerExceptions) toFlatten.Push(inner);
} else if (current.InnerException is not null) {
toFlatten.Push(current.InnerException);
}
}
}
/// <summary> /// <summary>
/// 获取 <paramref name="ex"/> 的用户友好描述。 /// 获取 <paramref name="ex"/> 的用户友好描述。
/// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。 /// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
@@ -62,7 +80,7 @@ public static class ExceptionExtensions {
lines.Reverse(); lines.Reverse();
return lines.Join(" ← "); return lines.Join(" ← ");
} else { } else {
return commonReason + "详细错误:" + lines.First(); return $"{commonReason}({lines.First()})";
} }
} }
} }
@@ -74,6 +92,8 @@ public static class ExceptionExtensions {
for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) { for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) {
if (currentEx is TimeoutException) { if (currentEx is TimeoutException) {
return true; return true;
} else if (currentEx is TaskCanceledException) {
return true;
} else if (currentEx is HttpRequestCodeException reqEx) { } else if (currentEx is HttpRequestCodeException reqEx) {
if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false; if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false;
if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true; if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true;
+22 -27
View File
@@ -96,11 +96,12 @@ public static class StringExtensions {
/// 若原始字符串为空,则返回 {""}。 /// 若原始字符串为空,则返回 {""}。
/// </summary> /// </summary>
public static string[] Split(this string fullStr, string splitStr) { public static string[] Split(this string fullStr, string splitStr) {
if (splitStr.IsSingle()) if (splitStr.IsSingle()) {
return fullStr.Split(splitStr[0]); return fullStr.Split(splitStr[0]);
else } else {
return fullStr.Split([splitStr], StringSplitOptions.None); return fullStr.Split([splitStr], StringSplitOptions.None);
} }
}
/// <summary> /// <summary>
/// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。 /// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
@@ -108,10 +109,8 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
if (pos >= 0) if (pos < 0) return str;
return str.Substring(0, pos); return str.Substring(0, pos);
else
return str;
} }
/// <summary> /// <summary>
/// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。 /// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
@@ -119,10 +118,8 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
if (pos >= 0) if (pos < 0) return str;
return str.Substring(0, pos); return str.Substring(0, pos);
else
return str;
} }
/// <summary> /// <summary>
@@ -131,10 +128,8 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string AfterFirst(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string AfterFirst(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
if (pos >= 0) if (pos < 0) return str;
return str.Substring(pos + text!.Length); return str.Substring(pos + text!.Length);
else
return str;
} }
/// <summary> /// <summary>
/// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。 /// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
@@ -142,10 +137,8 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase); int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
if (pos >= 0) if (pos < 0) return str;
return str.Substring(pos + text!.Length); return str.Substring(pos + text!.Length);
else
return str;
} }
/// <summary> /// <summary>
@@ -155,19 +148,21 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string Between(this string str, string after, string before, bool ignoreCase = false) { public static string Between(this string str, string after, string before, bool ignoreCase = false) {
int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase); int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
if (startPos >= 0) if (startPos >= 0) {
startPos += after.Length; startPos += after.Length;
else } else {
startPos = 0; startPos = 0;
}
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase); int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
if (endPos >= 0) if (endPos >= 0) {
return str.Substring(startPos, endPos - startPos); return str.Substring(startPos, endPos - startPos);
else if (startPos > 0) } else if (startPos > 0) {
return str.Substring(startPos); return str.Substring(startPos);
else } else {
return str; return str;
} }
}
#endregion #endregion
@@ -175,20 +170,20 @@ public static class StringExtensions {
/// <summary> /// <summary>
/// 替换字符串中的内容。 /// 替换字符串中的内容。
/// 仅当需要替换时,才调用 <paramref name="newValue"/> 获取结果字符串。 /// 仅当需要替换时,才调用 <paramref name="newValueGetter"/> 获取结果字符串。
/// </summary> /// </summary>
public static string ReplaceOnDemand(this string str, string oldValue, Func<string> newValue) => public static string Replace(this string str, string oldValue, Func<string> newValueGetter) =>
str.Contains(oldValue) ? str.Replace(oldValue, newValue()) : str; str.Contains(oldValue) ? str.Replace(oldValue, newValueGetter()) : str;
/// <summary> /// <summary>
/// 将字符串中的换行符统一替换为指定字符。 /// 将字符串中的换行符统一替换为指定字符。
/// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。 /// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
/// </summary> /// </summary>
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) => public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) {
Regex.Replace(input, return (mergeMultiple ? regexLineEndingAndMerge : regexLineEnding).Replace(input, newValue.Replace("$", "$$")); // 避免识别成捕获组
mergeMultiple ? @"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+" : @"\r\n|[\n\r\f\u0085\u2028\u2029]", }
newValue.Replace("$", "$$"), // 避免识别成捕获组 private static readonly Regex regexLineEndingAndMerge = new(@"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+", RegexOptions.Compiled);
RegexOptions.Compiled); private static readonly Regex regexLineEnding = new(@"\r\n|[\n\r\f\u0085\u2028\u2029]", RegexOptions.Compiled);
#endregion #endregion
+17 -9
View File
@@ -9,7 +9,6 @@ namespace MeloongCore;
public enum LogLevels { public enum LogLevels {
/// <summary> /// <summary>
/// 追踪。 /// 追踪。
/// 只在调试状态下输出日志信息。
/// </summary> /// </summary>
Trace, Trace,
/// <summary> /// <summary>
@@ -59,19 +58,23 @@ public enum LogBehaviors {
public static class Logger { public static class Logger {
public static BaseLogger Instance { get; set; } = new(); public static BaseLogger Instance { get; set; } = new();
// 转发给实例的方法调用 // 转发给实例的方法包装
public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "")
=> Instance.Log(message, level, behavior, filePath); => Instance.Log(message, level, behavior, filePath);
public static void Log(Exception ex, string? message = null, LogLevels level = LogLevels.Warning, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Instance.Log(ex, message, level, behavior, filePath);
public static void Trace(Func<string> message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") { if (Instance.MinLevel <= LogLevels.Trace) Log(message(), LogLevels.Trace, behavior, filePath); }
public static void Trace(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath); public static void Trace(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath);
public static void Info(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Info, behavior, filePath); public static void Info(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Info, behavior, filePath);
public static void Warning(string message, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath); public static void Warning(string message, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath);
public static void Error(string message, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath); public static void Error(string message, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath);
public static void Log(Func<string> messageGetter, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") {
if (Instance.MinLevel <= level) Instance.Log(messageGetter(), level, behavior, filePath); }
public static void Trace(Func<string> messageGetter, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(messageGetter, LogLevels.Trace, behavior, filePath);
public static void Info(Func<string> messageGetter, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(messageGetter, LogLevels.Info, behavior, filePath);
public static void Warning(Func<string> messageGetter, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(messageGetter, LogLevels.Warning, behavior, filePath);
public static void Error(Func<string> messageGetter, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(messageGetter, LogLevels.Error, behavior, filePath);
public static void Log(Exception ex, string? message = null, LogLevels level = LogLevels.Warning, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Instance.Log(ex, message, level, behavior, filePath);
public static void Trace(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Trace, behavior, filePath); public static void Trace(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Trace, behavior, filePath);
public static void Info(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Info, behavior, filePath); public static void Info(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Info, behavior, filePath);
public static void Warning(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Warning, behavior, filePath); public static void Warning(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Warning, behavior, filePath);
@@ -113,7 +116,7 @@ public class BaseLogger {
/// 格式化日志文本。 /// 格式化日志文本。
/// </summary> /// </summary>
protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) { protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) {
string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{filePath.AfterLast(@"\").BeforeFirst(".")}] "; string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{Path.GetFileName(filePath).BeforeFirst(".")}] ";
return text return text
.ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries) .ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries)
.Select(t => prefix + t) .Select(t => prefix + t)
@@ -139,7 +142,7 @@ public class BaseLogger {
/// 将日志输出到 <see cref="Debug"/> 并写入指定的文件夹,最多保留 5 个文件。 /// 将日志输出到 <see cref="Debug"/> 并写入指定的文件夹,最多保留 5 个文件。
/// 不实现 <see cref="LogBehaviors"/>。 /// 不实现 <see cref="LogBehaviors"/>。
/// </summary> /// </summary>
public class FileLogger : BaseLogger { public class FileLogger : BaseLogger, IDisposable {
/// <inheritdoc/> /// <inheritdoc/>
protected override void Output(string formattedText, LogLevels level) { protected override void Output(string formattedText, LogLevels level) {
@@ -205,4 +208,9 @@ public class FileLogger : BaseLogger {
thread.Start(); thread.Start();
} }
public void Dispose() {
writerAvaliable = false;
if (writer is not null) ((IDisposable) writer).Dispose();
queuedEvent.Dispose();
}
} }