Files
ACP/Logger/LoggerHelper.cs
2026-07-29 13:12:27 +08:00

113 lines
3.6 KiB
C#

using NLog;
using System;
using System.Collections.Generic;
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 scope, string message, string color, int depth)> Progress { get; set; }
static LoggerHelper()
{
Progress = new Progress<(string scope, string message, string color, int depth)>();
}
public static void InfoWithNotify(string scope, string message, int depth = 0)
{
Logger.Info(message);
NotifyUI(scope, message, "blue", depth);
}
public static void SuccessWithNotify(string scope, string message, int depth = 0)
{
Logger.Info(message);
NotifyUI(scope, message, "lightgreen", depth);
}
public static void WarnWithNotify(string scope, string message, string stackTrace = null, int depth = 0)
{
if (!string.IsNullOrEmpty(stackTrace))
{
string location = GetProjectStackLine(stackTrace);
message = $"{message} ({location})";
}
Logger.Warn(message);
NotifyUI(scope, message, "orange", depth);
}
public static void ErrorWithNotify(string scope, string message, string stackTrace = null, int depth = 0)
{
if (!string.IsNullOrEmpty(stackTrace))
{
string location = GetProjectStackLine(stackTrace);
message = $"{message} ({location})";
}
Logger.Error(message);
NotifyUI(scope, message, "red", depth);
}
private static void NotifyUI(string scope, string message, string color, int depth)
{
Progress.Report((scope, message, color, depth));
}
public static void Info(string message, int depth = 0)
{
Logger.Info(message);
}
public static void Success(string message, int depth = 0)
{
Logger.Info(message);
}
public static void Warn(string message, string stackTrace = null, int depth = 0)
{
if (!string.IsNullOrEmpty(stackTrace))
{
string location = GetProjectStackLine(stackTrace);
message = $"{message} ({location})";
}
Logger.Warn(message);
}
public static void Error(string message, string stackTrace = null, int depth = 0)
{
if (!string.IsNullOrEmpty(stackTrace))
{
string location = GetProjectStackLine(stackTrace);
message = $"{message} ({location})";
}
Logger.Error(message);
}
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("ACP"))
{
var match = Regex.Match(line, @"in (.+?):line (\d+)");
if (match.Success)
{
return match.Value;
}
return line.Trim();
}
}
return lines[0].Trim();
}
}
}