using System;
using System.Globalization;
using System.Text;
namespace TeamAAS
{
///
/// 统一的进程内日志入口(底层经 NLog 写文件,见 TeamAAS.Logging.NLogHub)。
/// 日志写入 CommonPattern 解析出的公共日志文件(如 Logs/年/年-月-日.log),与插件 1/2 级日志共用;
/// 单文件大小归档与保留天数自动删除均由 NLog 原生完成(配置见 PluginLogConfig)。
/// 写日志失败不会反向影响业务流程,只会回退到 Debug 输出,避免异常处理路径再次抛出异常。
///
public static class AppLogger
{
/// 是否启用文件日志。
public static bool Enabled { get; set; } = true;
/// 低于该级别的日志不会写入文件。
public static LogLevel MinimumLevel { get; set; } = LogLevel.Info;
public static void Info(string message, string source = null) => Write(LogLevel.Info, message, null, source);
public static void Warning(string message, string source = null) => Write(LogLevel.Warning, message, null, source);
public static void Error(string message, string source = null) => Write(LogLevel.Error, message, null, source);
public static void Error(string message, Exception exception, string source = null) => Write(LogLevel.Error, message, exception, source);
///
/// 写入一条日志。该方法刻意不向调用方抛出异常,适合在 catch/finally 中使用。
///
public static void Write(LogLevel level, string message, Exception exception = null, string source = null)
{
if (!Enabled || level < MinimumLevel)
return;
var now = DateTime.Now;
var safeMessage = message ?? string.Empty;
var builder = new StringBuilder();
builder.Append(now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
builder.Append(" [").Append(level.ToString().ToUpperInvariant()).Append("]");
builder.Append(" [T").Append(Environment.CurrentManagedThreadId).Append("]");
if (!string.IsNullOrWhiteSpace(source))
builder.Append(" [").Append(source.Trim()).Append("]");
builder.Append(' ').Append(safeMessage.Replace(Environment.NewLine, " | "));
if (exception != null)
{
builder.Append(" | ").Append(exception.GetType().FullName);
builder.Append(": ").Append(exception.Message);
if (!string.IsNullOrWhiteSpace(exception.StackTrace))
builder.AppendLine().Append(exception.StackTrace);
}
var line = builder.ToString();
try
{
TeamAAS.Logging.NLogHub.Apply();
TeamAAS.Logging.NLogHub.Common.Log(MapLevel(level), line);
}
catch (Exception loggingException)
{
System.Diagnostics.Debug.WriteLine("[TeamAAS logging failure] " + loggingException.Message);
System.Diagnostics.Debug.WriteLine(line);
}
// 联动实时日志控件:公共日志条目(已受 Enabled/MinimumLevel 过滤),恒显示
TeamAAS.Logging.LogStream.Publish(new TeamAAS.Logging.LogEntry(
now, TeamAAS.Logging.LogSource.Common, level,
sourceTag: source,
message: exception == null ? safeMessage : safeMessage + " | " + exception.Message));
}
private static NLog.LogLevel MapLevel(LogLevel level)
{
switch (level)
{
case LogLevel.Warning: return NLog.LogLevel.Warn;
case LogLevel.Error: return NLog.LogLevel.Error;
default: return NLog.LogLevel.Info;
}
}
}
///
/// 日志类别(精简为三档),数值越大代表严重程度越高。
///
public enum LogLevel
{
Info = 0,
Warning = 1,
Error = 2
}
}