86 lines
2.9 KiB
C#
86 lines
2.9 KiB
C#
using NLog;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Logger
|
|
{
|
|
public static class LoggerHelper
|
|
{
|
|
public static readonly ILogger Logger = LogManager.GetLogger("InfoLogger");
|
|
public static readonly ILogger sqlLogger = LogManager.GetLogger("SqlLogger");
|
|
public static IProgress<(string message, string color,int depth)> Progress { get; set; }
|
|
static LoggerHelper()
|
|
{
|
|
Progress = new Progress<(string message, string color, int depth)>();
|
|
}
|
|
public static void InfoWithNotify(string message, int depth=0)
|
|
{
|
|
Logger.Info(message); // 写入 NLog
|
|
NotifyUI(message, "blue", depth); // 触发UI显示
|
|
}
|
|
|
|
public static void SuccessWithNotify(string message, int depth=0)
|
|
{
|
|
Logger.Info(message);
|
|
NotifyUI(message, "lightgreen", depth);
|
|
}
|
|
public static void WarnWithNotify(string message, string stackTrace = null, int depth = 0)
|
|
{
|
|
if (!string.IsNullOrEmpty(stackTrace))
|
|
{
|
|
string location = GetProjectStackLine(stackTrace);
|
|
message = $"{message} ({location})";
|
|
}
|
|
|
|
Logger.Warn(message);
|
|
NotifyUI(message, "orange", depth);
|
|
}
|
|
|
|
public static void ErrorWithNotify(string message, string stackTrace = null, int depth = 0)
|
|
{
|
|
if (!string.IsNullOrEmpty(stackTrace))
|
|
{
|
|
string location = GetProjectStackLine(stackTrace);
|
|
message = $"{message} ({location})";
|
|
}
|
|
|
|
Logger.Error(message);
|
|
NotifyUI(message, "red", depth);
|
|
}
|
|
private static void NotifyUI(string message, string color, int depth)
|
|
{
|
|
Progress.Report((message, color, depth));
|
|
}
|
|
// 解析堆栈,找到项目文件路径和行号
|
|
public static string GetProjectStackLine(string stackTrace)
|
|
{
|
|
if (string.IsNullOrEmpty(stackTrace))
|
|
return "未知位置";
|
|
|
|
var lines = stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
foreach (var line in lines)
|
|
{
|
|
// 匹配你项目的命名空间路径
|
|
if (line.Contains("BOB"))
|
|
{
|
|
// 提取 "in 文件路径:line 行号"
|
|
var match = Regex.Match(line, @"in (.+?):line (\d+)");
|
|
if (match.Success)
|
|
{
|
|
return match.Value; // 返回类似 C:\...\MainViewModel.cs:line 37
|
|
}
|
|
return line.Trim();
|
|
}
|
|
}
|
|
|
|
return lines[0].Trim(); // 如果找不到就返回第一条
|
|
}
|
|
}
|
|
}
|